[英]Python regex capturing groups not working for simple expression
我想为两个连续的单词获取2个捕获的组。 我使用以下正则表达式:
r'\b(hello)\b(world)\b'
但是,使用此正则表达式搜索“ hello world”不会产生任何结果:
regex = re.compile(r'\b(hello)\b(world)\b')
m = regex.match('hello world') # m evaluates to None.
您需要在单词之间留出空格:
>>> import re
>>> regex = re.compile(r'\b(hello)\s*\b(world)\b')
>>> regex.match('hello world')
<_sre.SRE_Match object at 0x7f6fcc249140>
>>>
正则表达式\\b(hello)\\b(world)\\b
要求单词hello
恰好在单词world
起始位置处结束,但它们之间的分隔符为\\b
。 那不可能发生。 在它们之间添加空格\\s
可以解决此问题。
如果您打算允许hello
和world
之间使用标点符号或其他分隔符,则应将这种可能性添加到正则表达式中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.