在Python中重复捕获奇怪的resu

2024-03-28 10:41:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我想重复一遍,让自然数出现,并抓住所有的自然数。你知道吗

import re
r = "the ((sixty|six)[ -]+)+items"
s = "the sixty six items"
re.findall(r, s)
# [('six ', 'six')]

它与'six'匹配了2次,但是可以观察到,它不可能在'six-six'上匹配;相反,它必须在'six-six'上匹配,但是捕获返回('six','six')。你知道吗

这里发生了什么,我怎么才能回来(‘六十’、‘六’)?你知道吗


Tags: theimportreitemssixfindallsixty
3条回答

如果使用(group)+,则组中只捕获最后匹配的文本。你知道吗

您应该将findall与稍微不同的regex一起使用。你知道吗

s = 'the sixty six items'

>>> if re.match(r'the (?:(?:sixty|six)[ -]+)+items', s):
...     re.findall(r"\b(sixty|six)[ -]+(?=.*\bitems\b)", s)
...
['sixty', 'six']

您的问题有以下代码:

>>> r = "the ((sixty|six)[ -]+)+items"
>>> s = "the sixty six items"
>>> re.findall(r, s)

它返回[('six ', 'six')],因为在你的组后面使用了量词,即((sixty|six)[ -]+)+

findall返回两个

  1. captured group #1"six "(注意这里的空格是由于第一个组中的[ -]+
  2. captured group #2"six"(内部组,即(sixty|six)

使用\b断言:希望这有帮助。你知道吗

>>> s = "the sixty six items"
>>> print(re.findall(r'(?is)(\bsixty\b|\bsix\b)',s))
['sixty', 'six']

\b断言将避免错误命中,例如:如果您添加了十六个并且不希望匹配

没有\b

>>> s = "the sixty sixteen six items"
>>> print(re.findall(r'(?is)(sixty|six)',s))
['sixty', 'six', 'six']

\b(优势)

>>> s = "the sixty sixteen six items"
>>> print(re.findall(r'(?is)(\bsixty\b|\bsix\b)',s))
['sixty', 'six']

re.search只找到与模式匹配的第一个对象,一旦找到匹配的对象,它就不会再寻找其他匹配的对象。因为一个捕获组嵌套在另一个捕获组中,('six ', 'six')与外部组匹配,'six '与内部组匹配(没有尾随空格)。你知道吗

您可以在一些非捕获组中使用两个未嵌套的捕获组(使用(?:...)语法)来执行所需的操作。你知道吗

import re

r = "the (?:(?:(sixty)|(six))[ -]+)+items"
s = "the sixty six items"
m = re.search(r, s)
if m:
    print(m.groups())

输出

('sixty', 'six')

这将返回一个包含两个项的元组,因为模式中有两个捕获组。你知道吗

这是一个较长的演示。你知道吗

import re

pat = re.compile("the (?:(?:(sixty)|(six))[ -]+)+items")

data = (
    "the items",
    "the six items",
    "the six six items",
    "the sixty items",
    "the six sixty items",
    "the sixty six items",
    "the sixty-six items",
    "the six sixty sixty items",
)

for s in data:
    m = pat.search(s)
    print('{!r} -> {}'.format(s, m.groups() if m else None))  

输出

'the items' -> None
'the six items' -> (None, 'six')
'the six six items' -> (None, 'six')
'the sixty items' -> ('sixty', None)
'the six sixty items' -> ('sixty', 'six')
'the sixty six items' -> ('sixty', 'six')
'the sixty-six items' -> ('sixty', 'six')
'the six sixty sixty items' -> ('sixty', 'six')

相关问题 更多 >