2017-02-22 51 views
1

我目前用下面的正則表達式工作的第一位,以匹配電話號碼我需要一個正則表達式不接受0作爲3位數美國區號

'\\([1-9]{3}\\)\\s{1}[0-9]{3}-[0-9]{4}' 

但上面的電話號碼模式是不允許在前3位數字0,當我修改它爲

'\\([0-9]{3}\\)\\s{1}[0-9]{3}-[0-9]{4}' 

它接受0作爲第一位數字。我想生成一個正則表達式,它不會接受0的第一個數字,但確實接受其餘的數字。

我修改,我認爲會適合我的需要的正則表達式,但我不能完全肯定(永遠做一個正則表達式)和不知道如何測試它regex101

'\\([1-9]{1}[0-9]{2}\\)\\s{1}[0-9]{3}-[0-9]{4}' 

,如果有人能夠幫助我出去,如果你可以指出,如果我走在正確的方向,這將是驚人的

我在尋找什麼在這個問題的逆,在這個答案確保數字以0開頭,但我我正在尋找以下實施的反面

Javascript Regex - What to use to validate a phone number?

謝謝 維傑

+0

號電話例子嗎? –

+0

[Javascript正則表達式 - 用什麼來驗證電話號碼?]可能的重複(http://stackoverflow.com/questions/14639973/javascript-regex-what-to-use-to-validate-a-phone-number ) – Brian

+0

@Edulynch 電話號碼示例: - 208-123-4567 280-123-4567 – Vijay

回答

3

試試這個:

/\([1-9]\d\d\)\s\d{3}-\d{4}/; 

或者:

new RegExp('\\([1-9]\\d\\d\\)\\s\\d{3}-\\d{4}'); 

說明:

\( : open paren 
[1-9] : a digit (not 0) 
\d\d : 2 digits (including 0) 
\) : close paren 
\s : one space 
\d{3} : 3 digits (including 0) 
-  : hyphen 
\d{4} : 4 digits (including 0) 
+0

這是一個很好的解釋,但我不確定是否在www.regex101上正確測試它。com 我按照你的解釋進入測試的電話號碼是 (200)123-4567並且測試失敗,我做錯了什麼? – Vijay

+0

@Vijay這是它的工作https://www.regex101.com/r/IEvvhX/1。 –

+0

@Vijay注意:如果你使用這個正則表達式來測試一個字符串是否是一個有效的數字('regex.test(string)'),那麼你可能想在beginig('^')和end '$')如下所示:'/^\([1-9] \ d \ d \)\ s \ d {3} - \ d {4} $ /'。 –

1

這應該工作。

正則表達式:

[1-9]\d{2}\-\d{3}\-\d{4} 

輸入:

208-123-4567 
099-123-4567 
280-123-4567 

輸出:

208-123-4567 
280-123-4567 

JavaScript代碼:

const regex = /[1-9]\d{2}\-\d{3}\-\d{4}/gm; 
 
const str = `208-123-4567 
 
099-123-4567 
 
280-123-4567`; 
 
let m; 
 

 
while ((m = regex.exec(str)) !== null) { 
 
    // This is necessary to avoid infinite loops with zero-width matches 
 
    if (m.index === regex.lastIndex) { 
 
     regex.lastIndex++; 
 
    } 
 
    
 
    // The result can be accessed through the `m`-variable. 
 
    m.forEach((match, groupIndex) => { 
 
     console.log(`Found match, group ${groupIndex}: ${match}`); 
 
    }); 
 
}

參見:https://regex101.com/r/3DKEas/1

相關問題