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


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 ="\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?

6/26/2018 6:41:10 AM

Accepted Answer

Why don't you try

word = 'two'
re.compile(r'\b%s\b' % word, re.I)


>>> word = 'two'
>>> k = re.compile(r'\b%s\b' % word, re.I)
>>> x = 'one two three'
>>> y = x)
>>> y
<_sre.SRE_Match object at 0x100418850>

Also forgot to mention, you should be using raw strings in your code

>>> x = 'one two three'
>>> y ="\btwo\b", x)
>>> y
<_sre.SRE_Match object at 0x100418a58>
10/22/2010 8:33:40 AM

This will work:"\btwo\b", x)

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


or write a raw string like this:


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow