Regular expression to match US phone numbers

前端 未结 5 1294
臣服心动
臣服心动 2020-12-22 04:31

The regular expression ^((\\(\\d{3}\\) ?)|(\\d{3}-))?\\d{3}-\\d{4}$ matches strings of the form XXX-XXX-XXXX and XXX-XXXX (am I missin

5条回答
  •  滥情空心
    2020-12-22 04:58

    Your specification is a bit confusing. Your last two cases appear the same:
    XXX-XXX-XXXX
    XXX-XXXX
    (XXX) XXX-XXXX
    (XXX) XXX-XXXX

    (It looks like you're trying to match a phone number, is that right?) Assuming your last case is "(XXX)XXX-XXXX" (no space between area code and regular number, which I assume is the " ?" meaning optional space) then your RegExp is almost correct, just add two backslashes in front of the area code parentheses so they're matched as plain characters and not special grouping characters:

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

    Note that your regular expression may not have come through correctly, I noticed that stack overflow removed a single backslash from the RE pattern, I had to type a double backslash "\\" in order to get a single backslash to come out in the message

提交回复
热议问题