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
758 views
in Technique[技术] by (71.8m points)

regex - Regular Expression for matching a phone number

I need a regular expression to match phone numbers. I just want to know if the number is probably a phone number and it could be any phone format, US or international. So I developed a strategy to determine if it matches.

I want it to accept the following characters: 0-9 as well as ,.()- and optionally start with a + (for international numbers). The string should not match if it has any other characters.

I tried this:

/+?[0-9/.()-]/

But it matches phone numbers that have + in the middle of the number. And it matches numbers that contain alpha chars (I don't want that).

Lastly, I want to set the minimum length to 9 characters.

Any thoughts?

Thanks for any help, I'm obviously not too swift on RegEx stuff :)

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Well, you're pretty close. Try this:

^+?[0-9/.()-]{9,}$

Without the start and end anchors you allow partial matching, so it can match +123 from the string :-)+123.

If you want a minimum of 9 digits, rather than any characters (so ---.../// isn't valid), you can use:

^+?[/.()-]*([0-9][/.()-]*){9,}$

or, using a lookahead - before matching the string for [0-9/.()-]* the regex engine is looking for (D*d){9}, which is a of 9 digits, each digit possibly preceded by other characters (which we will validate later).

^+?(?=(D*d){9})[0-9/.()-]*$

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

...