正则表达式组匹配
我正在尝试搜索由空格分隔的二进制数字序列,如下所示:
>>> seq = '0 1 1 1 0 0 1 0'
因此,我创建了正则表达式:
>>> pat = r'(\b[01]\b)+'
但以下搜索仅返回一位数字:
>>> re.search(pat, seq).group(0)
'0'
出了什么问题?
I am trying to search for sequence of binary digits separated by white space like this:
>>> seq = '0 1 1 1 0 0 1 0'
so, I create the regex:
>>> pat = r'(\b[01]\b)+'
but following search returns only one digit:
>>> re.search(pat, seq).group(0)
'0'
What's wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你非常接近,只是图案中缺少一个空格。尝试
pat = r'\b([01] )*[01]\b'
You're very close, just missing a space in the pattern. Try
pat = r'\b([01] )*[01]\b'
您当前的正则表达式无法匹配空格,因此它只能匹配单个字符。您可以使用与
re.findall()
相同的正则表达式来获取字符串中的所有匹配项,也可以修改您的正则表达式,以便即使遇到空格也会继续匹配。以下是使用
re.findall()
的示例:或者通过将正则表达式更改为
(\b[01]\b\s?)+
您可以获得整个序列在单场比赛中:Your current regex has no way to match the whitespace, so it can only match a single character. You can either use the same regex with
re.findall()
to get all matches in the string, or modify your regex so it will continue matching even if it encounters white space.Here is an example using
re.findall()
:Or by changing the regex to
(\b[01]\b\s?)+
you can get the entire sequence in a single match: