正则表达式组匹配

发布于 2025-01-01 12:39:54 字数 288 浏览 2 评论 0原文

我正在尝试搜索由空格分隔的二进制数字序列,如下所示:

>>> 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

失眠症患者 2025-01-08 12:39:54

你非常接近,只是图案中缺少一个空格。尝试 pat = r'\b([01] )*[01]\b'

>>> import re
>>> seq = '0 1 1 1 0 0 1 0'
>>> pat = r'\b([01] )*[01]\b'
>>> re.search(pat, seq).group(0)
'0 1 1 1 0 0 1 0'
>>> re.search(pat, 'spam and 0 0 0 1 0eggs').group(0)
'0 0 0 1'

You're very close, just missing a space in the pattern. Try pat = r'\b([01] )*[01]\b'

>>> import re
>>> seq = '0 1 1 1 0 0 1 0'
>>> pat = r'\b([01] )*[01]\b'
>>> re.search(pat, seq).group(0)
'0 1 1 1 0 0 1 0'
>>> re.search(pat, 'spam and 0 0 0 1 0eggs').group(0)
'0 0 0 1'
宣告ˉ结束 2025-01-08 12:39:54

您当前的正则表达式无法匹配空格,因此它只能匹配单个字符。您可以使用与 re.findall() 相同的正则表达式来获取字符串中的所有匹配项,也可以修改您的正则表达式,以便即使遇到空格也会继续匹配。

以下是使用 re.findall() 的示例:

>>> re.findall(r'(\b[01]\b)+', '0 1 1 1 0 0 1 0')
['0', '1', '1', '1', '0', '0', '1', '0']

或者通过将正则表达式更改为 (\b[01]\b\s?)+ 您可以获得整个序列在单场比赛中:

>>> re.search(r'(\b[01]\b\s?)+', '0 1 1 1 0 0 1 0').group(0)
'0 1 1 1 0 0 1 0'

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():

>>> re.findall(r'(\b[01]\b)+', '0 1 1 1 0 0 1 0')
['0', '1', '1', '1', '0', '0', '1', '0']

Or by changing the regex to (\b[01]\b\s?)+ you can get the entire sequence in a single match:

>>> re.search(r'(\b[01]\b\s?)+', '0 1 1 1 0 0 1 0').group(0)
'0 1 1 1 0 0 1 0'
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文