Anan Anan - 3 months ago 13
Javascript Question

How to understand regex '\b'?

I am learning the regex.But I can't understand the '\b' , match a word boundary . there have three situation,like this:

  1. Before the first character in the string, if the first character is a word character.

  2. After the last character in the string, if the last character is a word character.

  3. Between two characters in the string, where one is a word character and the other is not a word character.

I can't understand the third situation.for example´╝Ü

var reg = /end\bend/g;
var string = 'wenkend,end,end,endend';
alert( reg.test(string) ) ; //false

The '\b' require a '\w' character at its one side , another not '\w' character at the other side . the string 'end,end' should match the rule, after the first character is string ',' , before the last character is string ',' , so why the result is error .Could you help,Thanks in advance!

============dividing line=============

With your help, I understand it. the /end\bend/g is not mean after the first character have a boundary ,before the last character have a boundary ,It's mean
this is not all '\w' character on both sides.

In other words ,the reg '/end\bend/g' or others similar reg aren't exit forever.
Thanks again


The \b matches position, not a character. So this regex /end\bend/g says that there must be string end. Then it should be followed by not a word character, which is , and it matches, but the regex engine doesn't move in the string and it stays at ,. So the next character in your regex is e, and e doesn't match ,. So regexp fails. Here is step by step what happens:

/end\bend/g,   "end,end"        (match)
   |              |

/end\bend/g,   "end,end"        (both regex and string position moved - match)
     |             |

/end\bend/g,   "end,end"        (the previous match was zero-length, so only regex position moved - not match)
      |            |