REGEX. What am I doing wrong?

  • Thread starter Thread starter shapper
  • Start date Start date
S

shapper

Hello,

I need to create a REGEX which accepts only phone numbers.

The phone numbers start allways with 261, 21, 96 or 91 and have 7
numbers after it.

Something like. 261 1223346, 21 2334456, etc.

I tried the following but it is not working:
^(?:261|21|96|91)\s\d{7}$

How can I do this?

Thanks,

Miguel
 
Hello,

I need to create a REGEX which accepts only phone numbers.

The phone numbers start allways with 261, 21, 96 or 91 and have 7
numbers after it.

Something like. 261 1223346, 21 2334456, etc.

I tried the following but it is not working:
^(?:261|21|96|91)\s\d{7}$

if (?:) means a noncapturing group then you need a parenthesis

^?:(261|21|96|91)\s\d{7}$
 
Hi there again,

I believe it should work. I'm note sure how you utilized this regular
expression but if you're trying validate user input via regular expression
validation control
ValidationExpression="^(261|21|96|91)\s*\d{7}$"
should be enough. Otherwise, if you try to validate and get both area code
this might be an idea how to do that:

string pattern = @"^(261|21|96|91)\s(\d{7})$";

System.Text.RegularExpressions.Match match =
System.Text.RegularExpressions.Regex.Match(
txtPhone.Text, pattern);

if (match.Success)
{
string areaCode = match.Groups[1].Value;
string number = match.Groups[2].Value;
}
else
{
// not valid
}
 
^((261)|(21)|(96)|(91))\s\d{7}$

works for me

Peter

Hi,

It really does not work. Please try:

' Create new regex
Dim regex As System.Text.RegularExpressions.Regex
regex = New RegularExpressions.Regex("^((261)|(21)|(96)|(91))\s
\d{7}$")

' Check if expression is a match
Response.Write(regex.IsMatch("961234567").ToString)

It returns False.

Any idea?

Thanks,
Miguel
 
Hi Alexey,

I also tried your suggestion and a few others and it does not work.

because of \s what mean a single space

regex = New RegularExpressions.Regex("^((261)|(21)|(96)|(91))\d{7}$")
 
The examples the OP gave were (I copy and paste):

261 1223346, 21 2334456

I assume that means a space is needed between the prefix and the last 7
digits.

So it still works for me on that basis.


Peter
 
You should have told us space is optional:

string pattern = @"^(261|21|96|91)\s*\d{7}$";

should do the job.
 
Back
Top