开发者

regex and javascript, some matches disappear !

Here is the code :

> var reg = new RegExp(" hel.lo ", 'g');
> 
> var str = " helalo helblo helclo heldlo ";
> 
> var mat = str.match(reg);
> 
> alert(mat);

It alerts "helalo, helclo", but i expect it to be "helalo, helblo, helclo, heldlo" . Only the half of them matches, I guess that's because of the space wich count only once. So I tried to double every space before processing, but in some case it's not enough. I'm looking for an expla开发者_如何学运维nation, and a solution.

Thx


  "␣helalo␣helblo␣helclo␣heldlo␣"
// 11111111------22222222-------

When ␣helalo␣ was matched, the string left is helblo␣... without the leading space. But the regex requires a leading space, so it skips to ␣helclo␣.

To avoid the expression eating up the space, use a lookahead.

var reg = / hel.lo(?= )/g

(Or use \b as a word boundary.)


It matches the regex, advances to the next character after the matched string and goes on.

You can use \b to match word boundaries. You can add the whitespaces later, if you want to.

\bhel.lo\b
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜