Reputation: 325
I want to create a regexp for phone number in jQuery. My code:
var name_regexp = /\(\+?([0-9]{2})\)?([ .-]?)([0-9]{3})\2([0-9]{3})\2([0-9]{1,3})/;
if (($phone).match(name_regexp))
/*do sth */
And I use this expression because I want to support sth like that (+11)111111111, but I am trying to support:
However, when I change expression to
var name_regexp = /\(?([0-9]{3})\)?([ .-]?)([0-9]{3})\2([0-9]{4})/;
I get no matches.
Upvotes: 2
Views: 794
Reputation: 627517
To match the numbers you supplied, you need to actually match one or zero spaces, dots or hyphens right after the area code inside parentheses, and only capture and back reference the delimiter after the first 3 digits:
/^(?:\(\+?[0-9]{2}\))?[ .-]?[0-9]{3}([ .-]?)[0-9]{3}\1[0-9]{1,3}$/
^^^^^^ ^^^^^^^^ ^
See the regex demo.
You also need to allow an optional +
at the beginning with \+?
, 2 digits inside parentheses, and the whole prefix should be made optional (=put inside an optional group with (?:...)?
).
Pattern details:
^
- start of string(?:\(\+?[0-9]{2}\))?
- 1 or 0 occurrences of:
\(
- one (
\+?
- one or zero +
[0-9]{2}
- 2 digits\)
- a closing )
[ .-]?
- 1 or 0 spaces, dots or hyphens[0-9]{3}
- 3 digits([ .-]?)
- Group 1 capturing the delimiter (a space, dot or hyphen)[0-9]{3}
- 3 digits\1
- the same delimiter captured into Group 1[0-9]{1,3}
- 1 to 3 digits$
- end of string.Upvotes: 1