1

I am trying the match the following possible scenarios. They are all phone numbers but they can be from anywhere in the world.

  • "92134"
  • "+234234"
  • "-234234"
  • "234(234)"
  • "(559) 559-5591 ext123"
  • "(559) 559-5591 EXT123"
  • "(559) 559-5591 Ext123"
  • "(559) 559-5591 x123"
  • "(559) 559-5591 X123"
  • "416.123.4567"

Now I'm not limiting the number of digits or anything but the key problems are the following.

Allow:

  • '()', '-', '.' anywhere in the string... start end e.t.c
  • '+' as the first character (Doesn't need to be though)
  • 'ext', 'Ex't, 'EXT', 'X', 'x' only for the last set of digits. So not (559) 559 EXt5591 EXT123

Now I have wrote the following but I do not know enough about Regex to optimize it more and get the result i want.

@"^(?=[0-9])([-.+ Ee Xx Tt \s()0-9])+$"

2
  • 1
    Perhaps you should let the field be free and live happy Commented May 1, 2015 at 15:07
  • I wish I could trust the clients that much :-( Commented May 1, 2015 at 15:10

1 Answer 1

1

You could use something like the following:

/^
(
(?:
    (?:^\+)               # matches the "+" sign at the beginning
  |
    (?:\(\d+\))           # matches '(' and its paired ')' but allows only digit inside
  |
    \d                    # matches a digit
  |
    [ .-]                 # matches a separator character
  |
    (?:(?>ext|x)\d{3}$)   # matches the EXT' part at the end
)+
)
$/ix

An example at: https://regex101.com/r/nC2vV4/1

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

6 Comments

Hi @Tiller, Thanks for the comment. Does this work for . net Regex also?
I'm sorry I've never touched .Net ; However AFAIK it should. The only touchy thing I see that could fail is my "(?>...)" which you would just have to replace by "(?:...)" if so.
I think it 'd be something like: @"(?i)^((?:(?:^\+)|(?:\(\d+\))|\d|[ .-]|(?:(?>ext|x)\d{3}$))+)$"
Weird, I'm using regexhero.net/tester and I canb't match anything. There must be something that .net doesn't like.
Everything works just fine for me on your website. Depending on what you're testing, you might want to activate the multiline-mode on the right side of your website.
|

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.