Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regular expression - /\w\b\w/

I am confused about /\w\b\w/. I think it should match "e w" in "we we", since:

\w is word character which is "e"

\b is word broundary which is " " (space)

\w is another word which is "w"

So the match is "e w" in "we we". But...

/\w\b\w/ will never match anything, because a word character can never be followed by both a non-word and a word character.

I got this one from MDN:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions?redirectlocale=en-US&redirectslug=JavaScript%2FGuide%2FRegular_Expressions

I can't understand their explanation. Can you help me explain it in baby step? Thank you!

  • Nick
like image 487
Nicolas S.Xu Avatar asked Jun 05 '26 14:06

Nicolas S.Xu


1 Answers

The space character isn't the word boundary. A word boundary isn't a character itself, it's the place "in between characters" where a word character transitions to a non-word character.

So "e w".match(/\w\b/) only matches "e", not "e ".

/\w\b\w/ never matches anything because it would require that a word character be immediately followed by a non-word character and also by a word character, which is of course not possible.

like image 65
Dagg Nabbit Avatar answered Jun 07 '26 03:06

Dagg Nabbit