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:
JavaScript
x
3
1
>>> x = 'one two three'
2
>>> y = re.search("btwob", x)
3
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?
Advertisement
Answer
You should be using raw strings in your code
JavaScript
1
6
1
>>> x = 'one two three'
2
>>> y = re.search(r"btwob", x)
3
>>> y
4
<_sre.SRE_Match object at 0x100418a58>
5
>>>
6
Also, why don’t you try
JavaScript
1
3
1
word = 'two'
2
re.compile(r'b%sb' % word, re.I)
3
Output:
JavaScript
1
7
1
>>> word = 'two'
2
>>> k = re.compile(r'b%sb' % word, re.I)
3
>>> x = 'one two three'
4
>>> y = k.search( x)
5
>>> y
6
<_sre.SRE_Match object at 0x100418850>
7