views:

33

answers:

2

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 explanation, and a solution.

Thx

+4  A: 
  "␣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.)

KennyTM
thank you =) that's exactly what i needed !
+1 in general, but the //11111111------22222222------- visualisation is very helpful for those first starting out in the painful world of regex!
MatW
+1  A: 

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
tiftik
the matter wuth the \b is that it will match for example ' :helalo: '