[英]Javascript, regular expression and {n,m}
I just noticed a very strange behaviour. 我刚刚注意到一种非常奇怪的行为。 Why does a simple space break all the tests? 为什么一个简单的空间会破坏所有测试?
rePattern = /^([a-z]+[-_]?){2,}[a-z]$/;
var test = new Array("jhgfg_hfh-g", "jhg-fg_hfhg", "jhg_fg_hfhg", "jhg_fg_hfhg", "jhg_fghfhg");
for (var i = 0; i < test.length ; i++) {
x = test[i];
alert(i + ' : ' + x + ' : ' + rePattern.test( x ));
}
if i change the above to 如果我改变上面的
// notice {2,} => {2, } with an extra space before }
rePattern = /^([a-z]+[-_]?){2, }[a-z]$/;
then everything become false
... 一切都变得false
......
thank u 感谢你
OK, just to have an accepted answer here: it's because of the extra space. 好的,只是在这里有一个接受的答案:这是因为额外的空间。 The syntax of regular expressions is strict, you can't add random whitespace and expect it'll be ignored. 正则表达式的语法是严格的,你不能添加随机空格并期望它会被忽略。 {2, }
will match literal {2, }
: {2, }
将匹配文字{2, }
:
/^x{2, }$/.test('x{2, }') === true
Your regexp does'nt work when you add a space at the begin or end of tested value because you use the regexp delemiters ^ and $ 当您在测试值的开头或结尾添加空格时,您的正则表达式不起作用,因为您使用regexp delemiters ^和$
If you combine the two delimiters, the regexp will react to all the caracters including the spaces. 如果将两个分隔符组合在一起,则正则表达式将对包括空格在内的所有字符进行响应。
So use the following regexp to catch any string which following the pattern : 因此,使用以下正则表达式来捕获遵循该模式的任何字符串:
/([a-z]+[-_]?){2,}[a-z]/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.