2015-10-15 61 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»