gpt4 book ai didi

python - 为什么我不能在 python 中匹配正则表达式的最后一部分?

转载 作者:行者123 更新时间:2023-11-28 16:29:14 25 4
gpt4 key购买 nike

我想匹配一个带有可选结尾的句子 'other (\\w+)'。例如,正则表达式应该匹配如下两个句子并提取单词'things':

  • 苹果和其他东西。
  • 苹果很大。

我写了一个正则表达式如下。但是,我得到了一个结果 (None,)。如果我删除最后一个 ?。我会得到正确的答案。为什么?

>>> re.search('\w+(?: other (\\w+))?', 'A and other things').groups()
(None,)
>>> re.search('\w+(?: other (\\w+))', 'A and other things').groups()
('things',)

最佳答案

如果您使用:

re.search(r'\w+(?: other (\w+))?', 'A and other things').group()

你会看到发生了什么。由于 \w+ 之后的任何内容都是可选的,因此您的 search 匹配第一个单词 A

根据 official documentation :

.groups()

Return a tuple containing all the subgroups of the match, from 1 up to however many groups are in the pattern.

并且您的 search 调用不会返回任何子组,因此您会得到:

re.search(r'\w+(?: other (\w+))?', 'A and other things').groups()
(None,)

要解决您的问题,您可以使用这个基于交替的正则表达式:

r'\w+(?: other (\w+)|$)'

示例:

>>> re.search(r'\w+(?: other (\w+)|$)', 'A and other things').group()
'and'
>>> re.search(r'\w+(?: other (\w+)|$)', 'The apple is big').group()
'big'

关于python - 为什么我不能在 python 中匹配正则表达式的最后一部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33717778/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com