[英]Regex to NOT match a string with 10 consecutive digits. The digits may be separated by white space. All other string return a match
我有一个通过 5/7 单元测试的 codepen。 卡在以非数字字符开头的字符串上。
https://codepen.io/david-grieve/pen/pBpGoO?editors=0012
var regexString = /^\D*(?!(\s*\d\s*){10,}).*/;
var regexString = /^\\D*(?!(\\s*\\d\\s*){10,}).*/; var tests = [{ text: 'abc123', ismatch: true }, { text: '1234567890', ismatch: false }, { text: '123456789', ismatch: true }, { text: 'abc1234567890efg', ismatch: false }, { text: '123 456 789 123', ismatch: false }, { text: 'abc1234567890', ismatch: false }, { text: '1234567890efg', ismatch: false } ]; console.log(new Date().toString()); tests.map(test => console.log(test.text, regexString.test(test.text) == test.ismatch));
使用此正则表达式,以下字符串通过单元测试
这些未通过单元测试
注意: /^\\D{3,}(?!(\\s*\\d\\s*){10,}).*/ 通过了所有的测试,但显然是错误的。
^\\D*(?!
的问题在于,即使在负前瞻中发现了一个长数字/空格字符串,一旦负前瞻匹配, \\D
匹配的部分将简单地回溯一个字符。例如,当
^\D*(?!\d{10,}).*
火柴
abc1234567890
\\D*
匹配ab
,而.*
匹配c1234567890
。 的之间的位置b
和c
不紧跟一个长数/空间子串,所以比赛不会失败。
另外,因为某些数字可能出现在10 个连续数字之前,所以开头的^\\D*
是不够的 - 例如,如果输入是1a01234567890
呢? 相反,尝试
^(?!.*(\d\s*){10}).*
这可以确保每个位置后面都没有(10 位数字,可能用空格分隔)。
https://regex101.com/r/v7t4IC/1
如果数字只能出现在字符串中的单个块中(可能用空格分隔),那么如果您处于支持所有格量词的环境中,您的模式就会起作用,从而防止回溯,例如:
^\D*+(?!(\s*\d\s*){10,}).*
^
https://regex101.com/r/eGdw2l/1
(但不幸的是,Javascript 不支持这种语法)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.