user3691716
user3691716

Reputation: 11

How to match the following pattern with regex?

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

Answers (2)

zx81
zx81

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

Ulugbek Umirov
Ulugbek Umirov

Reputation: 12807

With little modification it will be:

(((\(?\+?1?\)?)\s?[-.]?)?((\(?\d{3}\)?\s?[-.]?\s?))?\s?\d{3}\s?[-.]?\s?\d{3,4}){1}

Regular expression visualization

Original one:

Regular expression visualization

Upvotes: 1

Related Questions