0

I'm a newbie at using regex in c# and I'm trying to use it to validate a phone number with this format 09oxoxxxxxx where x can be any number and o can be only 1-9 and the total length should be 11 numbers. Here's what I think which is probably wrong.

if (Regex.IsMatch("09203041152", "^[0]{1}[9]{1}[1-9]{2}[1-9]{1}[0-9]{6}"))
2
  • shouldn't be 11 or should be 11? Commented Nov 25, 2013 at 7:04
  • Sorry was a typo, fixed now Commented Nov 25, 2013 at 7:18

4 Answers 4

2

You can use shorthand character \d which represents any number [0-9]:

Regex.IsMatch("09203041152", @"^09[1-9]\d[1-9]\d{6}$")

Your patter is not working due to repetitions count {2} here:

^[0]{1}[9]{1}[1-9]{2}[1-9]{1}[0-9]{6}

That requires two non-zero numbers in a row. But you need one non-zero number and one any number at this place:

^[0]{1}[9]{1}[1-9]{1}[0-9]{1}[1-9]{1}[0-9]{6}

Note - you don't need to specify repetitions count equal to {1}, because that means single token occurrence, which is true without specifying that explicitly.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for explaining why it is not working. for some reason your post wasn't here when I checked answers :\ up voted
@arashmoeen possibly you didn't refresh browser :)
If I had added some answer, I would have never tried to explain how the OP's code was wrong, +1 for that :) sometimes the best answer is not the accepted answer.
@lazyberezovsky Oh I sure did, because I didn't left the page open. that's strange. thanks anyways
1

The following RegExp should match the format you stated '09oxoxxxxxx'

^09[1-9][0-9][1-9][0-9]{6}$

Comments

1

Your regular expression is a bit more complex that it needs to be:

^09[1-9][0-9][1-9][0-9]{6}$
  • ^: Match the start-of-line.
  • 09: Matches the number 0 followed by 0.
  • [1-9]: Matches any number between 1 and 9.
  • [0-9]: Matches any number between 0 and 9.
  • [1-9]: Again matches any number between 1 and 9.
  • [0-9]{6}: Matches any number between 0 and 9 six times.
  • Now the total number of digits matched is 11.

2 Comments

sorry Udi was faster, but I up voted you for explaining the structure, cleared many things for me. Thanks a bunch
@arashmoeen Yes he was. Don't worry about it, you are welcome.
0

Try this:

^09[1-9][0-9][1-9][0-9]{6}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.