regular expression for indian phone number - c#

am looking for the regular expression of indian phone number
the regular expression should allow all the following formats.
for landline no
0802404408
080-2404408
+91802404408
+91-802404408
for mobile no
8147708287
08147708287
+918147708287
+91-8147708287
can anyone help me, thanks in advance
my code is
[RegexValidator("[0-9 -]*"
, MessageTemplateResourceName = "INVALID_PHONE"
, MessageTemplateResourceType = typeof(ValidatioinErrors))]
public string Phone
{
get { return phone; }
set { phone = value; }
}
public bool IsValid()
{
return Validation.Validate<Class_name>(this).IsValid;
}
public ValidationResults ValResults
{
get
{
return Validation.Validate<Class_name>(this);
}
}
for this validation thing I just referred
using Microsoft.Practices.EnterpriseLibrary.Validation;
using Microsoft.Practices.EnterpriseLibrary.Validation.Validators;
in my namespace, in the UI part the expression is working fine, but in the code behind as above, it shows "Invalid Phone number", if I give value as 080-2404408

You can try
^\+?[0-9-]+$
See it here on Regexr
The important parts are the anchors ^ and $ for the start and the end of the string. I added also \+? at the start, to match an optional +. The + needs to be escaped since it is a special character in regex, the ? after it makes it optional.
Of course this is a very simple pattern, be aware that e.g. "-----" would also be valid.

For the examples provided following RegEx works:
/^(?:\+91(?:-)?|0\d{2,4}-|0|)\d{7,10}$/

import re
mystr = """
8147708287
08147708287
+918147708287
+91-8147708287
"""
print(re.findall(r'\b91-*\d{10}',mystr))

Related

How to check if a textbox starts with numeric value

In Windows forms C#, I want to check if a textbox I made starts with a numeric value, then if it does I want to insert the minus (-) sign at the beginning to change the number to negative, I found a way but it's too time wasting, here's my code:
if (richTextBox1.Text.StartsWith("1") || richTextBox1.Text.StartsWith("2") #until richTextBox1.Text.StartsWith("9"))
{
richTextBox1.Text.Insert(0, "-");
}
So I was asking, if there's a shorter way to replace that code?
if (Char.IsNumber(richTextBox1.Text[0]))...
You should also add some checks around it to make sure there's text.
Using regex:
if (Regex.IsMatch(richTextBox1.Text, #"^\d"))
Matches a digit (0-9) at the start of the string.
Or a direct replace:
richTextBox1.Text = Regex.Replace(richTextBox1.Text, #"^\d", "-$&");
Checking if the first character of a text is a number can be done in single line, using Char.IsNumber() function as follows:
if ( Char.IsNumber( stringInput, 0) ) {
// String input begins with a number
}
More information:
https://learn.microsoft.com/en-us/dotnet/api/system.char.isnumber
Many good answer's already here, another alternative is if you want culture support give this a try...
public static bool IsNumber(char character)
{
try
{
int.Parse(character.ToString(), CultureInfo.CurrentCulture);
return true;
}
catch (FormatException) { return false; }
}
You can call it like:
if ( IsNumber(richTextBox1.Text[0]))

Syntax Highlighting in FlowDocumentControl for RScript

We have use the following Regex function to highlight the string and numeric
String Regex function
public string StringRegEx
{
get { return #"#?""""|#?"".*?(?!\\).""|''|'.*?(?!\\).'"; }
}
Numeric Regex function
public string NumberRegEX
{
get { return #"[0-9].*?(?=:[0-9]*)?"; }
}
while using this regex function we have face some issues for highlighting string contains numeric
p1 = 1
p2 = 0.2
In this example, 1 and 2 in p1 and p2 also highlighted. How to skip the number highlighted along with the string?
For a more general approach on how to properly catch things when dealing with a programming language snippet, take a look here.
Your problem might not be "comments in strings, strings in comments" but it is similar, namely "letters in a string that started with a number, numbers in a string that started with a letter" so you'll need a similar approach with pipe-separated regexes for the different matches you wanna have.
A more thorough explanation of this design-pattern is given here.

Regular Expression for allowing multiple language input

Quick question regarding regular expression validation on textbox entry. Basically I have a textbox that I am using for user input in the form of a website address. The user can input anything (it doesn't have to be a valid website address - i.e. www.facebook.com. They could enter "blah blah", and that's fine but it will not run.
What I am after is to validate different languages, Arabic, Greek, Chinese, etc etc, because at present I only allow English characters.
The code for the method is below. I believe I will have to switch this from a whitelist to blacklist, so instead of seeing what matches, change the expression to invalid characters, and if the user enters one of these, don't allow it.
public static bool IsValidAddress(string path)
{
bool valid = false;
valid = (path.Length > 0);
if (valid)
{
string regexPattern = #"([0-9a-zA-Z*?]{1})([-0-9a-zA-Z_\.*?]{0,254})";
// Elimate the '"' character first up so it simplifies regular expressions.
valid = (path.Contains("\"") == false);
if (valid)
{
valid = IsValidAddress(path, regexPattern);
}
if (valid)
{
// Need an additional check to determine that the address does not begin with xn--,
// which is not permitted by the Internationalized Domain Name standard.
valid = (path.IndexOf("xn--") != 0);
}
}
return valid;
}
As you can see, I have the 0-9a-zA-Z included, but by default this will eliminate other languages, whereas I wish to include the languages.
Any help is greatly appreciated. If I've confused anyone, sorry! I can give more information if it is needed.
Thanks.
I don't know why you're trying to validate Uri's with Regex. .Net's Uri class is surely a much better match to your task, no?
Uri uri;
if(!Uri.TryParse(uriString, UriKind.Absolute, out uri))
{
//it's a bad URI
}

regular expression validation errors

I have a problem with regular expression validation, see If I put the validation in code behind like,
[RegexValidator("[0-9 -]*"
, MessageTemplateResourceName = "INVALID_PHONE"
, MessageTemplateResourceType = typeof(ValidatioinErrors))]
public string Phone
{
get { return phone; }
set { phone = value; }
}
and if I give the value for phone as "080-244408" like this its working but if I give "080-2404408", that is one extra digit it shows error as "Invalid phone". What is the reason. can anyone help me, thanks in advance.
Doesn't look like a problem with your regex. You need to give more information on this. Something else might be wrong in your code.

Check for special characters (/*-+_#&$#%) in a string?

How do I check a string to make sure it contains numbers, letters, or space only?
In C# this is simple:
private bool HasSpecialChars(string yourString)
{
return yourString.Any(ch => ! char.IsLetterOrDigit(ch));
}
The easiest way it to use a regular expression:
Regular Expression for alphanumeric and underscores
Using regular expressions in .net:
http://www.regular-expressions.info/dotnet.html
MSDN Regular Expression
Regex.IsMatch
var regexItem = new Regex("^[a-zA-Z0-9 ]*$");
if(regexItem.IsMatch(YOUR_STRING)){..}
string s = #"$KUH% I*$)OFNlkfn$";
var withoutSpecial = new string(s.Where(c => Char.IsLetterOrDigit(c)
|| Char.IsWhiteSpace(c)).ToArray());
if (s != withoutSpecial)
{
Console.WriteLine("String contains special chars");
}
Try this way.
public static bool hasSpecialChar(string input)
{
string specialChar = #"\|!#$%&/()=?»«#£§€{}.-;'<>_,";
foreach (var item in specialChar)
{
if (input.Contains(item)) return true;
}
return false;
}
String test_string = "tesintg#$234524##";
if (System.Text.RegularExpressions.Regex.IsMatch(test_string, "^[a-zA-Z0-9\x20]+$"))
{
// Good-to-go
}
An example can be found here: http://ideone.com/B1HxA
If the list of acceptable characters is pretty small, you can use a regular expression like this:
Regex.IsMatch(items, "[a-z0-9 ]+", RegexOptions.IgnoreCase);
The regular expression used here looks for any character from a-z and 0-9 including a space (what's inside the square brackets []), that there is one or more of these characters (the + sign--you can use a * for 0 or more). The final option tells the regex parser to ignore case.
This will fail on anything that is not a letter, number, or space. To add more characters to the blessed list, add it inside the square brackets.
Use the regular Expression below in to validate a string to make sure it contains numbers, letters, or space only:
[a-zA-Z0-9 ]
You could do it with a bool. I've been learning recently and found I could do it this way. In this example, I'm checking a user's input to the console:
using System;
using System.Linq;
namespace CheckStringContent
{
class Program
{
static void Main(string[] args)
{
//Get a password to check
Console.WriteLine("Please input a Password: ");
string userPassword = Console.ReadLine();
//Check the string
bool symbolCheck = userPassword.Any(p => !char.IsLetterOrDigit(p));
//Write results to console
Console.WriteLine($"Symbols are present: {symbolCheck}");
}
}
}
This returns 'True' if special chars (symbolCheck) are present in the string, and 'False' if not present.
A great way using C# and Linq here:
public static bool HasSpecialCharacter(this string s)
{
foreach (var c in s)
{
if(!char.IsLetterOrDigit(c))
{
return true;
}
}
return false;
}
And access it like this:
myString.HasSpecialCharacter();
private bool isMatch(string strValue,string specialChars)
{
return specialChars.Where(x => strValue.Contains(x)).Any();
}
Create a method and call it hasSpecialChar with one parameter
and use foreach to check every single character in the textbox, add as many characters as you want in the array, in my case i just used ) and ( to prevent sql injection .
public void hasSpecialChar(string input)
{
char[] specialChar = {'(',')'};
foreach (char item in specialChar)
{
if (input.Contains(item)) MessageBox.Show("it contains");
}
}
in your button click evenement or you click btn double time like that :
private void button1_Click(object sender, EventArgs e)
{
hasSpecialChar(textbox1.Text);
}
While there are many ways to skin this cat, I prefer to wrap such code into reusable extension methods that make it trivial to do going forward. When using extension methods, you can also avoid RegEx as it is slower than a direct character check. I like using the extensions in the Extensions.cs NuGet package. It makes this check as simple as:
Add the [https://www.nuget.org/packages/Extensions.cs][1] package to your project.
Add "using Extensions;" to the top of your code.
"smith23#".IsAlphaNumeric() will return False whereas "smith23".IsAlphaNumeric() will return True. By default the .IsAlphaNumeric() method ignores spaces, but it can also be overridden such that "smith 23".IsAlphaNumeric(false) will return False since the space is not considered part of the alphabet.
Every other check in the rest of the code is simply MyString.IsAlphaNumeric().
Based on #prmph's answer, it can be even more simplified (omitting the variable, using overload resolution):
yourString.Any(char.IsLetterOrDigit);
No special characters or empty string except hyphen
^[a-zA-Z0-9-]+$

Categories

Resources