re 模块中的正则表达式是否支持单词边界 (\b)? [英] Do regular expressions from the re module support word boundaries (\b)?
本文介绍了re 模块中的正则表达式是否支持单词边界 (\b)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在尝试了解更多有关正则表达式的知识时,一个教程建议您可以使用 \b
来匹配单词边界.但是,Python 解释器中的以下代码段无法按预期工作:
如果有任何匹配,它应该是一个匹配对象,但它是None
.
Python 不支持 \b
表达式还是我使用错误?
解决方案
为什么不试试
word = '二're.compile(r'\b%s\b' % word, re.I)
输出:
<预><代码>>>>字 = '两个'>>>k = re.compile(r'\b%s\b' % word, re.I)>>>x = '一二三'>>>y = k.search( x)>>>是<_sre.SRE_Match 对象在 0x100418850>还忘了说,你应该使用原始字符串 在你的代码中
<预><代码>>>>x = '一二三'>>>y = re.search(r"\btwo\b", x)>>>是<_sre.SRE_Match 对象在 0x100418a58>>>>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?
解决方案
Why don't you try
word = 'two'
re.compile(r'\b%s\b' % word, re.I)
Output:
>>> 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>
Also forgot to mention, you should be using raw strings in your code
>>> x = 'one two three'
>>> y = re.search(r"\btwo\b", x)
>>> y
<_sre.SRE_Match object at 0x100418a58>
>>>
这篇关于re 模块中的正则表达式是否支持单词边界 (\b)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文