Saturday, October 27, 2018

c# - Regex optional white space in phone number











I am pretty close to a full regex that I need. However I can't seem to get an optional white space allowed.



Regex



^(\(?\d{3}\)?\-?\d{3}\-?\d{4})$



Requirements - Only these four



111-111-1111 - Works



(111)111-1111 - Works



(111) 111-111 - Doesn't Capture



1111111111 - Works




How do I add an optional space after the parenthesis?


Answer



How about \(?\b[0-9]{3}\)?[-. ]?[0-9]{3}[-. ]?[0-9]{4}\b which matches 3334445555, 333.444.5555, 333-444-5555, 333 444 5555, (333) 444 5555 and all combinations thereof.



Updated



You're running into the limitations of REGEX and so the ugly solution really is:



(\d{3}-\d{3}-\d{4}|\(\d{3}\)\s?\d{3}-\d{4}|\d{10})



Example


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...