Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
769 views
in Technique[技术] by (71.8m points)

regex - Regular expression to match US phone numbers

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

It doesn't, however, match (XXX) XXX-XXXX and (XXX) XXX-XXX-XXXX as well (which I need it to match).

Can you help me fix it so that it matches the formats
???? XXX-XXX-XXXX, XXX-XXXX, (XXX) XXX-XXXX, (XXX) XXX-XXXX
without causing it to match other string formats which I don't want?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...