2015-10-15 64 views
-2

我想在JS中設計一個正則表達式匹配包含7-14連續數字的字符串。如何匹配正則表達式只有當它匹配

我有以下

var regex = /[^a-zA-Z]\d{6,15}[^a-zA-Z]/g; 

但是,當我有以下字符串測試,它失敗。

var test = "111222333444555666"; 

它接受匹配的前14位數字,這不是我想要的。我只想匹配如果我的正則表達式沒有被其他數字包圍並且沒有被字符包圍。

我可以天真地撲通[^a-zA-Z\d]在正則表達式的結尾,但我覺得有一個更簡單的方法。

有什麼建議嗎?

感謝, erip

+0

「我想設計一個正則表達式」 分裂? –

+0

'test.match(regex);' – erip

+3

如果我理解正確,你可以在輸入的開始/結束處使用錨點,如下所示:'/^\ d {7,14} $ /'這將確保輸入包含只有7 - 14位數字,僅此而已。 – neuronaut

回答

1

Word boundaries\b將檢查一個數量並不,前面和後面通過[A-Za-z0-9_]

代碼

var regex = /\b\d{7,14}\b/g 
 
var test = "abc 111222333444555666 1234 123456789 123456789xyz"; 
 

 
// print all matches 
 
while ((m = regex.exec(test)) !== null) { 
 
    if (m.index === regex.lastIndex) { 
 
     regex.lastIndex++; 
 
    } 
 
    
 
    document.writeln("<br />Match: " + m[0]); 
 
}

+0

因爲'+','-'和'.'不是單詞字符。因此,'\ b'只會匹配像'c'這樣的單詞字符。 – Mariano

+0

然後用相反的'\ B'匹配非單詞邊界'/ \ B [ - +] \ d {7,14} \ b /' – Mariano

0

我想,如果我正則表達式不被其他數字所包圍, 不是字符圍繞只匹配。

if (/\b[\da-z]{7,14}\b/.test(subject)) { 
    // Successful match 
} else { 
    // Match attempt failed 
} 

Regex的說明

\b[\da-z]{7,14}\b 

Assert position at a word boundary «\b» 
Match a single character present in the list below «[\da-z]{7,14}» 
    Between 7 and 14 times, as many times as possible, giving back as needed (greedy) «{7,14}» 
    A 「digit」 «\d» 
    A character in the range between 「a」 and 「z」 «a-z» 
Assert position at a word boundary «\b»