Regular Expression for matching a phone number

后端 未结 3 1647
不思量自难忘°
不思量自难忘° 2020-12-10 20:51

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

相关标签:
3条回答
  • 2020-12-10 21:05

    The juqeury has a plugin for US phone validation. Check this link. You can also see the regular expression in the source code.

    0 讨论(0)
  • 2020-12-10 21:07

    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\/.()-]*$
    
    0 讨论(0)
  • 2020-12-10 21:09

    The reason why it matches alpha character is because of the period. You have to escape it. I don't know what editor you are using for this, this is what I'll use for VIM:

    ^+\?[()\-\.]\?\([0-9][\.()\-]\?\)\{3,\}$
    
    0 讨论(0)
提交回复
热议问题