gpt4 book ai didi

python - re.findall 给出的结果与具有相同模式的 re.search 不同

转载 作者:行者123 更新时间:2023-11-30 22:07:16 31 4
gpt4 key购买 nike

我有一个 str,我想获取单引号内的子字符串 ('):

line = "This is a 'car' which has a 'person' in it!"

所以我用了:

name = re.findall("\'(.+?)\'", line)
print(name[0])
print(name[1])

car
person

但是当我尝试这种方法时:

pattern = re.compile("\'(.+?)\'")
matches = re.search(pattern, line)
print(matches.group(0))
print(matches.group(1))
# print(matches.group(2)) # <- this produces an error of course

'car'
car

所以,我的问题是为什么该模式在每种情况下表现不同?我知道前者返回“字符串中模式的所有非重叠匹配”,而后者匹配对象可能会解释一些差异,但我期望相同的模式有相同的结果(即使是不同的格式)。

所以,为了更具体:

  1. 在第一种情况下,findall 模式返回所有子字符串,但在后一种情况下,它仅返回第一个子字符串。
  2. 在后一种情况下,matches.group(0)(根据文档对应于 the whole match)与 matches.group(1)(对应于第一个带括号的子组)。这是为什么?

re.finditer("\'(.+?)\'", line) 返回匹配对象,因此其功能类似于 re.search

我知道有类似的问题,比如这个 one 或这个 one 但他们似乎没有回答为什么(或者至少我没有得到它)​​。

最佳答案

您已经阅读了文档和其他答案,所以我将为您提供实践解释

我们首先以here中的这个例子为例

>>> m = re.match(r"(\w+) (\w+)", "Isaac Newton, physicist")
>>> m.group(0) # The entire match
'Isaac Newton'
>>> m.group(1) # The first parenthesized subgroup.
'Isaac'
>>> m.group(2) # The second parenthesized subgroup.
'Newton'
>>> m.group(1, 2) # Multiple arguments give us a tuple.
('Isaac', 'Newton')

如果你继续this website你会发现与之前的检测的对应关系

first example

组(0)正在进行全场比赛,组(1)和组(2)分别是图中的组1和组2。因为正如所说的here "Match.group([group1, ...])返回匹配的一个或多个子组。如果只有一个参数,则结果是一个字符串;如果有多个参数,则结果是一个元组,每个参数包含一项。如果没有参数,group1 默认为零(返回整个匹配项)”

现在让我们回到您的示例

second example

正如其他人用 re.search(pattern, line) 所说,您只会找到该模式的第一次出现 [“扫描字符串,查找正则表达式模式产生的第一个位置匹配”如所述here ] 并按照前面的逻辑,您现在将了解为什么 matches.group(0) 将输出完整匹配项,而 matches.group(1) 将输出第 1 组。您将理解为什么 matches.group(2) 给你错误[因为你可以从屏幕截图中看到,在最后一个例子中第一次出现时没有组 2]

关于python - re.findall 给出的结果与具有相同模式的 re.search 不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52500279/

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