Do regular expressions from the re module support word boundaries (\b)?

D.C. picture D.C. · Oct 22, 2010 · Viewed 57k times · Source

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 snippet in the Python interpreter does not work as expected:

>>> x = 'one two three'
>>> y = re.search("\btwo\b", x)

It should have been a match object if anything was matched, but it is None.

Is the \b expression not supported in Python or am I using it wrong?

Answer

Bolo picture Bolo · Oct 22, 2010

This will work: re.search(r"\btwo\b", x)

When you write "\b" in Python, it is a single character: "\x08". Either escape the backslash like this:

"\\b"

or write a raw string like this:

r"\b"