REGEX. What am I doing wrong?

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
 
G

Guest

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}$
 
G

Guest

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
}
 
S

shapper

^((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
 
G

Guest

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}$")
 
P

Peter Bradley

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
 
G

Guest

You should have told us space is optional:

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

should do the job.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,162
Latest member
GertrudeMa
Top