c# regex spain mobile phone

3.6k views Asked by At

what would be a valid regex for these rules:

34 6xx xxx xxx 
34 7yx xxx xxx
(note y cannot be 0 (zero))

would this one work?

34(([6][0-9]{8}$)|([7][1-9]{1}[0-9]{7}$))
2

There are 2 answers

1
Sergey Kalinichenko On BEST ANSWER

Your regular expression should work, assuming that you are not expecting it to handle spaces.

You can further optimize your regex by extracting the common suffix of [0-9]{7} from it:

^34(?:6[0-9]|7[1-9])[0-9]{7}$

If you would like to account for optional spaces, insert \s? into your regex in places where you wish to allow space characters to be inserted:

^34\s?(?:6[0-9]|7[1-9])[0-9]\s?[0-9]{3}\s?[0-9]{3}$
1
Wiktor Stribiżew On

If you need to handle this specific format with spaces, you can use

^34 ?(?:6[0-9]{2}|7[1-9][0-9])(?: ?[0-9]{3}){2}$

See RegexStorm demo

REGEX EXPLANATION:

  • ^ - Start of string
  • 34 ? - 34 followed by an optional space
  • (?:6[0-9]{2}|7[1-9][0-9]) - A group of 2 alternatives: 6 can be followed by any 2 digits, and 7 can be followed only by non-0 and one more digit
  • (?: ?[0-9]{3}){2} - 2 groups of 3 digits, optionally separated with a space
  • $ - End of string.