Reputation: 11
I have a regular exp as follows (((\(?\+?1?\)?)\s?-?)?((\(?\d{3}\)?\s?-?\s?))?\s?\d{3}\s?-?\s?\d{4}){1}
it matches the numbers in this format xxx-xxx-xxxx
; where x are digits from 0-9. How can I make it to match the numbers also with dots(.) for example xxx.xxx.xxxx
and also to match with xxx.xxx.xxx
Upvotes: 0
Views: 57
Reputation: 41838
A simpler regex
I would suggest simplifying the regex to this (see demo of what matches and doesn't match):
^\d{3}([-.])\d{3}\1\d{3,4}$
One benefit of this expression is that we ensure that the same delimiter -
or .
is used between the groups of digits. We do this by capturing the delimiter to group 1 using ([-.])
, then by referencing that capture later using \1
.
Explanation:
^ # assert position at the beginning of the string
\d{3} # match any digit from 0-9 (3 times)
( # group and capture to \1
[-.] # match any character in the list: '-', '.'
) # end of first capturing group
\d{3} # any digit from 0-9 (3 times)
\1 # what was matched by group 1
\d{3,4} # match any digit (0-9) (3 or 4 times)
$ # assert position at the end of the string (before an optional \n)
Upvotes: 3
Reputation: 12807
With little modification it will be:
(((\(?\+?1?\)?)\s?[-.]?)?((\(?\d{3}\)?\s?[-.]?\s?))?\s?\d{3}\s?[-.]?\s?\d{3,4}){1}
Original one:
Upvotes: 1