I want to write a regular expression to tack a number in Google Analytics for a specific US phone number that supports the following formats: ###-###-#### (###) ###-#### ### ### #### ###.###.####
where #
means a specific number.
I need it written so that I can track a different phone number in the future by just swapping out the digits as needed.
So far I came up with this to validate a phone number that is in the different formats I'm looking for, but I'm having trouble understanding how to change it in order to validate a specific phone number, not just a general one. How would I track the phone (630) 321-4321 specifically for example?
This is how far I got:
^\+?\d{0,3}\s?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}$
Like I mentioned above, this will validate a general phone number but I need a specific number, not a general one.
Best Answer
I'd say:
Explaination:
^
: String start\(?\d{3}\)?
: That would match 3 numbers, with or without()
. In this case the parentheses have a special meaning in regexp, so you have to escape them. Parentheses may or may not be in the expression, so that's why I placed the?
just after.[. -]
: One of these characters follow. Although the point has a special meaning in regexp, in defined in a set you don't have to escape it.\d{3}
: Just another 3 digits.[. -]
: Another separator. Either a.
, or a-
, or a space.\d{4}
: Just another 4 digits.$
: String end.