[英]Regex to NOT match a string with 10 consecutive digits. The digits may be separated by white space. All other string return a match
I have a codepen with 5/7 unit tests passing.我有一个通过 5/7 单元测试的 codepen。 Stuck on strings starting with non-digit characters.
卡在以非数字字符开头的字符串上。
https://codepen.io/david-grieve/pen/pBpGoO?editors=0012 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));
With this regex the following strings pass the unit tests使用此正则表达式,以下字符串通过单元测试
These fail the unit tests这些未通过单元测试
Note: /^\\D{3,}(?!(\\s*\\d\\s*){10,}).*/ passes all the tests but is obviously wrong.注意: /^\\D{3,}(?!(\\s*\\d\\s*){10,}).*/ 通过了所有的测试,但显然是错误的。
The problem with ^\\D*(?!
is that, even if a long digit/space string is found in the negative lookahead, the part matched by \\D
will simply backtrack one character once the negative lookahead matches. Eg, when ^\\D*(?!
的问题在于,即使在负前瞻中发现了一个长数字/空格字符串,一旦负前瞻匹配, \\D
匹配的部分将简单地回溯一个字符。例如,当
^\D*(?!\d{10,}).*
matches火柴
abc1234567890
the \\D*
matches ab
, and the .*
matches c1234567890
. \\D*
匹配ab
,而.*
匹配c1234567890
。 The position between the b
and the c
is not immediately followed by a long number/space substring, so the match does not fail.的之间的位置
b
和c
不紧跟一个长数/空间子串,所以比赛不会失败。
Also, because some digits may come before the 10 consecutive digits, the ^\\D*
at the beginning won't be enough - for example, what if the input is 1a01234567890
?另外,因为某些数字可能出现在10 个连续数字之前,所以开头的
^\\D*
是不够的 - 例如,如果输入是1a01234567890
呢? Instead, try相反,尝试
^(?!.*(\d\s*){10}).*
This ensures that every position is not followed by (10 digits, possibly separated by spaces).这可以确保每个位置后面都没有(10 位数字,可能用空格分隔)。
https://regex101.com/r/v7t4IC/1 https://regex101.com/r/v7t4IC/1
If the digits can only come in a single block (possibly separated by spaces) in the string, your pattern would've worked if you were in an environment which supports possessive quantifiers, which prevent backtracking, eg:如果数字只能出现在字符串中的单个块中(可能用空格分隔),那么如果您处于支持所有格量词的环境中,您的模式就会起作用,从而防止回溯,例如:
^\D*+(?!(\s*\d\s*){10,}).*
^
https://regex101.com/r/eGdw2l/1 https://regex101.com/r/eGdw2l/1
(but Javascript does not support such syntax, unfortunately) (但不幸的是,Javascript 不支持这种语法)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.