How does \b work when using regular expressions?
The \b
token is kind of special. It doesn't actually match a character. What it does is it matches any position that lies at the boundary of a word (where "word" in this case is anything that matches \w
). So the pattern (?<=brown\s)(\w+)
would match "bbbbrown fox", but (?<=\bbrown\s)(\w+)
wouldn't, since the position between "bb" and "brown" is in the middle of a word, not at its boundary.
\b
is a zero width assertion. That means it does not match a character, it matches a position with one thing on the left side and another thing on the right side.
The word boundary \b
matches on a change from a \w
(a word character) to a \W
a non word character, or from \W
to \w
Which characters are included in \w
depends on your language. At least there are all ASCII letters, all ASCII numbers and the underscore. If your regex engine supports unicode, it could be that there are all letters and numbers in \w
that have the unicode property letter or number.
\W
are all characters, that are NOT in \w
.
\bbrown\s
will match here
The quick brown fox
^^
but not here
The quick bbbbrown fox
because between b and brown is no word boundary, i.e. no change from a non word character to a word character, both characters are included in \w
.
If your regex comes to a \b
it goes on to the next char, thats the b
from brown. Now the \b
know's whats on the right side, a word char ==> the b
. But now it needs to look back, to let the \b
become TRUE, there needs to be a non word character before the b
. If there is a space (thats not in \w
) then the \b
before the b
is true. BUT if there is another b
then its false and then \bbrown
does not match "bbrown"
The regex brown
would match both strings "quick brown" and "bbrown", where the regex \bbrown
matches only "quick brown" AND NOT "bbrown"
For more details see here on www.regular-expressions.info