【问题标题】:Why the output of re.findalll and re.finditer are different when using parenthesis? [duplicate]为什么使用括号时 re.findalll 和 re.finditer 的输出不同? [复制]
【发布时间】:2018-06-15 07:49:59
【问题描述】:

在 Python 3.6 中,与 re.finditer 相比,为什么 re.findall 在以下示例中返回不同的项目?

text = "He was carefully disguised but captured quickly by 10 caps."

print(re.findall(r"ca(p)", text))

for i in re.finditer(r"ca(p)", text):
    print(i)

findall 返回['p', 'p'],而 finditer 返回两个“cap”。只有当我使用括号时才会发生!

【问题讨论】:

  • 您是指(p) 处的括号吗?你知道这些是捕获组吗?阅读有关这两种方法的文档,了解它们如何处理捕获组。

标签: python regex python-3.x findall


【解决方案1】:

finditer 返回一个包含所有捕获组的匹配对象的可迭代对象,当您打印匹配对象时,它返回包含整个匹配字符串的第一个匹配组。

如果您希望字符串与捕获的组匹配,您需要使用group() 方法,该方法接受捕获的组数作为其参数。

for i in re.finditer(r"ca(p)", text):
    print(i.group(1))

另一方面,re.findall() 在列表中返回与您的正则表达式中所有捕获的组匹配的字符串。大致相当于以下finditer()代码:

[i for m in re.finditer(r"ca(p)", text) for i in m.groups()]

【讨论】:

  • 请解释您投反对票的原因!
  • 谢谢。看来我需要通过 group、groups 和 findall() 括号的功能和作用才能理解它。顺便说一句,我没有投反对票。
猜你喜欢
  • 1970-01-01
  • 2019-07-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-31
  • 2017-04-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多