简体   繁体   中英

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 ...

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, } :

/^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 $

  • ^ says that the pattern catch to the start of the string
  • $ says that the pattern catch to the end of the string

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]/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM