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) |
如果有匹配的对象,它应该是匹配对象,但它是
python中是否不支持
这是可行的:
用python编写
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.
为了明确解释为什么
1 2 | print("foo\bbar") fobar |
所以模式
为了允许