簡體   English   中英

移動電話號碼的正則表達式使國別代碼的選區為可選,破折號,點和空格為可選

[英]Regex for mobile number make parathesis as optional for country code and dashes, dots and spaces are optional

^(?([0-9]{3})?)[-. ]?([0-9]{3})[-. ]?([0-9]{4})$

我正在嘗試使用此正則表達式來驗證我想允許以下格式的手機號碼

1234567890
123-456-7890
123.456.7890
123 456 7890
(123)4567890
(123)-456-7890
(123).456.7890
(123) 456 7890

請幫助糾正正則表達式

您可以使用具有后向引用的捕獲組來獲取一致的定界符,並通過交替使用來獲取帶或不帶括號的版本,例如123-456.7890(123-456-7890不是有效的匹配項。

^(?:\(\d{3}\)([-. ]?)\d{3}\1\d{4}|\d{3}([-. ]?)\d{3}\2\d{4})$
  • ^字符串的開頭
  • (?:非捕獲組
    • \\(\\d{3}\\)匹配( ,3位數字和)
    • ([-. ]?)捕獲組1 ,可選地匹配- . 或空間
    • \\d{3}\\1\\d{4}匹配3位數字,反向引用組1和4位數字
    • | 要么
    • \\d{3}匹配3位數字
    • ([-. ]?)捕獲組2 ,可以選擇匹配- . 或空間
    • \\ d {3} \\ 2 \\ d {4}`匹配3位數字,向后引用組2和4位數字
  • )
  • $字符串結尾

正則表達式演示

 let pattern = /^(?:\\(\\d{3}\\)([-. ]?)\\d{3}\\1\\d{4}|\\d{3}([-. ]?)\\d{3}\\2\\d{4})$/; [ "1234567890", "123-456-7890", "123.456.7890", "123 456 7890", "(123)4567890", "(123)-456-7890", "(123).456.7890", "(123) 456 7890", "(123-456-7890", "123-456.7890" ].forEach(s => console.log(s + " --> " + pattern.test(s))); 

你可以用這個

^\(?[0-9]{3}\)?[\-\.\s]?\(?[0-9]{3}\)?[\-\.\s]?\(?[0-9]{4}\)?$

在這里測試https://regex101.com/

()是正則表達式的特殊字符,因此您需要對其進行轉義,以使其可選,您可以使用?

您可以將樣式更改為此

^([0-9]{3}|\([0-9]{3}\))([-. ]?)([0-9]{3})\2([0-9]{4})$

Regex Demo

 const regex = /^([0-9]{3}|\\([0-9]{3}\\))([-. ]?)([0-9]{3})\\2([0-9]{4})$/gm; const str = `1234567890 123-456-7890 123.456.7890 123 456 7890 (123)4567890 (123)-456-7890 (123).456.7890 (123) 456 7890 (123 456 7890 (123 456 7890 123-456.7890`; let m; while ((m = regex.exec(str)) !== null) { if (m.index === regex.lastIndex) { regex.lastIndex++; } m.forEach((match, groupIndex) => { console.log(`Found match, group ${groupIndex}: ${match}`); }); console.log('------') } 

大概是這樣

var patt = new RegExp('\\(?[0-9]{3}\\)?[.-\\s]?[0-9]{3}[.-\\s]?[0-9]{4}');

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM