关于正则表达式:来自re模块的Python正则表达式是否支持单词boundary()?

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

在试图学习更多关于正则表达式的知识时,教程建议你可以使用EDCOX1的0个词来匹配单词边界。但是,python解释器中的以下代码段不能按预期工作:

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

如果有匹配的对象,它应该是匹配对象,但它是None

python中是否不支持\b表达式,或者我是否使用了错误的表达式?


这是可行的:re.search(r"\btwo\b", x)

用python编写"\b"时,它是一个单独的字符:"\x08"。或者像这样避开反斜杠:

1
"\\b"

或者写一个这样的原始字符串:

1
r"\b"


你为什么不试试呢

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

输出:

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

还忘了提一下,您应该在代码中使用原始字符串

1
2
3
4
5
>>> x = 'one two three'
>>> y = re.search(r"\btwo\b", x)
>>> y
<_sre.SRE_Match object at 0x100418a58>
>>>


Python文档

https://docs.python.org/2/library/re.html正则表达式语法

\b

Matches the empty string, but only at the beginning or end of a word. A word is defined as a sequence of alphanumeric or underscore characters, so the end of a word is indicated by whitespace or a non-alphanumeric, non-underscore character. Note that formally, \b is defined as the boundary between a \w and a \W character (or vice versa), or between \w and the beginning/end of the string, so the precise set of characters deemed to be alphanumeric depends on the values of the UNICODE and LOCALE flags. For example, r'\bfoo\b' matches 'foo', 'foo.', '(foo)', 'bar foo baz' but not 'foobar' or 'foo3'. Inside a character range, \b represents the backspace character, for compatibility with Python’s string literals.


为了明确解释为什么re.search("\btwo\b", x)不起作用,这是因为python字符串中的\b是退格字符的缩写。

1
2
print("foo\bbar")
fobar

所以模式"\btwo\b"是寻找退格,后面跟着two,后面跟着另一个退格,你在其中搜索的字符串(x = 'one two three')没有。

为了允许re.searchcompile将序列\b解释为一个词的边界,可以避开反斜杠("\\btwo\\b"或使用原始字符串创建模式(r"\btwo\b")。