开发者

Confusion in JavaScript RegExp ? Quantifier

May I know the reason of getting the output of the followi开发者_运维技巧ng code as: 1,10,10? Why not it is as: 10, 10?

<script type="text/javascript">
var str="1, 100 or 1000?";
var patt1=/10?/g; 
document.write(str.match(patt1));
</script> 


Because the ? is a special character in regex, it's an operator makes the single item before it optional. Thus, /10?/ matches a 1 optionally followed by a 0. Hence why it can match just 1, or the 10 in 100, or the 10 in 1000.


this is a handy cheat sheet for reg expressions.

the bit that you need is in the middle:

  • 0 or more matches = *
  • 0 or 1 matches = ?
  • 1 or more matches = +

you can see the different effects these have, using your code, here


? is a meta-character meaning zero-or-more matches.

To match '?', escape.

var pat = /10\?/g;


It looks like you may be confusing the precedence

/10?/

This applies ? only to 0. If you want 10 to be modified with ?, then you'd have to group it:

/(10)?/

Or, if you don't need to capture:

/(?:10)?/

Similarly,

/ab+/

Matches abbbbbb. If you want to match ababab, then you'd have to write:

/(?:ab)+/


Fixed:

/10+\?/g
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜