Regular expression to match phone numbers with cou

2020-03-30 05:15发布

This is the regular expression I use to match phone numbers like:

00 00 00 00 00
00 00 0 00 00 00 00
+00 0 00 00 00 00

(\d{2}\s+\d{2}\s+\d{2}\s+\d{2}\s+\d{2})\s+(\d{2}\s+\d{2}\s+\d\s+\d{2}\s+\d{2}\s+\d{2}\s+\d{2})\s+(+\d{2}\s+\d\s+\d{2}\s+\d{2}\s+\d{2}\s+\d{2})

I have tried to include it into my javascript but It's not really working

if(document.maj_profil.phone.value.search(/^\(\d{2}\s+\d{2}\s+\d{2}\s+\d{2}\s+\d{2}\)\s+\(\d{2}\s+\d{2}\s+\d\s+\d{2}\s+\d{2}\s+\d{2}\s+\d{2}\)\s+\(+\d{2}\s+\d\s+\d{2}\s+\d{2}\s+\d{2}\s+\d{2}\)/) == -1)
    {
    displayDialog('wrong phone format')
        }

5条回答
Animai°情兽
2楼-- · 2020-03-30 05:56

Try this:

var re = /^\+?(\d{1,2} ?)+$/g
var phone = "00 00 00 00 00"; //"00 00 00 00 00x"; 
if(!re.test(phone))
    alert("wrong phone pattern");
查看更多
何必那么认真
3楼-- · 2020-03-30 05:58
  1. Where you have your alternative formats listed like:

    (...)\s+(...)\s+(...)
    

    Change that to use the | (OR) operator:

    (...)|(...)|(...)
    
  2. Don't escape the parentheses. \( and \) should be simply ( and ).

  3. In your third group the + at the beginning should be escaped with a backslash:

    (\+\d{2}\s+\d\s+\d{2}\s+\d{2}\s+\d{2}\s+\d{2})
    
查看更多
smile是对你的礼貌
4楼-- · 2020-03-30 06:02

In the javascript, you have escaped all the brackets. Do you want them to behave as capturing groups, or do you want to match actual brackets in the string?

Also use test instead of search. test returns true or false, not a number.

查看更多
做自己的国王
5楼-- · 2020-03-30 06:14

Escaping the parenthesis turns them into literals. Try it without the escapes:

/^(\d{2}\s+\d{2}\s+\d{2}\s+\d{2}\s+\d{2})\s+(\d{2}\s+\d{2}\s+\d\s+\d{2}\s+\d{2}\s+\d{2}\s+\d{2})\s+(\d{2}\s+\d\s+\d{2}\s+\d{2}\s+\d{2}\s+\d{2})/
查看更多
可以哭但决不认输i
6楼-- · 2020-03-30 06:19

Try this instead:

\d\d(\s+\d\d){4}|(\d\d\s+\d\d\s+\d|\+\s+\d)\d\d(\s+\d\d){3}

which means:

\d\d(\s+\d\d){4}    // 00 00 00 00 00

|                   // OR

(                   // (
  \d\d\s+\d\d\s+\d  //    00 00 0
  |                 //    OR
  \+\s+\d           //    + 0
)                   // )
\d\d(\s+\d\d){3}    // 00 00 00 00
查看更多
登录 后发表回答