While trying to learn a little more about regular expressions, a tutorial suggested that you can use the \\b
to match a word boundary. However, the following sn
Just to explicitly explain why re.search("\btwo\b", x)
doesn't work, it's because \b
in a Python string is shorthand for a backspace character.
print("foo\bbar")
fobar
So the pattern "\btwo\b"
is looking for a backspace, followed by two
, followed by another backspace, which the string you're searching in (x = 'one two three'
) doesn't have.
To allow re.search
(or compile
) to interpret the sequence \b
as a word boundary, either escape the backslashes ("\\btwo\\b"
) or use a raw string to create your pattern (r"\btwo\b"
).