gpt4 book ai didi

Python re.finditer match.groups() 不包含匹配的所有组

转载 作者:行者123 更新时间:2023-11-28 21:20:13 28 4
gpt4 key购买 nike

我正在尝试在 Python 中使用正则表达式来查找并打印来自多行搜索的所有匹配行。我正在搜索的文本可能具有以下示例结构:

AAAABC1ABC2ABC3AAAABC1ABC2ABC3ABC4ABCAAAABC1AAA

From which I want to retrieve the ABC*s that occur at least once and are preceeded by an AAA.

The problem is, that despite the group catching what I want:

match = <_sre.SRE_Match object; span=(19, 38), match='AAA\nABC2\nABC3\nABC4\n'>

...我只能访问该组的最后一场比赛:

match groups = ('AAA\n', 'ABC4\n')

下面是我用来解决这个问题的示例代码。

#! python
import sys
import re
import os

string = "AAA\nABC1\nABC2\nABC3\nAAA\nABC1\nABC2\nABC3\nABC4\nABC\nAAA\nABC1\nAAA\n"
print(string)

p_MATCHES = []
p_MATCHES.append( (re.compile('(AAA\n)(ABC[0-9]\n){1,}')) ) #
matches = re.finditer(p_MATCHES[0],string)

for match in matches:
strout = ''
gr_iter=0
print("match = "+str(match))
print("match groups = "+str(match.groups()))
for group in match.groups():
gr_iter+=1
sys.stdout.write("TEST GROUP:"+str(gr_iter)+"\t"+group) # test output
if group is not None:
if group != '':
strout+= '"'+group.replace("\n","",1)+'"'+'\n'
sys.stdout.write("\nCOMPLETE RESULT:\n"+strout+"====\n")

最佳答案

这是你的正则表达式:

(AAA\r\n)(ABC[0-9]\r\n){1,}

Regular expression visualization

Debuggex Demo

您的目标是捕获所有 ABC#紧跟在AAA 之后。正如您在此 Debuggex 演示中所见,所有 ABC# 确实都匹配(它们以黄色突出显示)。但是,由于只有“正在重复的内容”部分

ABC[0-9]\r\n

正在captured (在括号内)及其 quantifier ,

{1,}

没有被捕获,因此这导致所有匹配除了最后一个被丢弃。要获得它们,您还必须捕获量词:

AAA\r\n((?:ABC[0-9]\r\n){1,})

Regular expression visualization

Debuggex Demo

我已将“正在重复的内容”部分 (ABC[0-9]\r\n) 放入 non-capturing group 中. (我也停止捕获 AAA,因为你似乎不需要它。)

捕获的文本可以在换行符上拆分,并会根据需要为您提供所有片段。

(请注意,\n 本身在 Debuggex 中不起作用。它需要 \r\n。)


这是一个解决方法。没有多少正则表达式风格提供通过重复捕获进行迭代的能力(哪些......?)。更正常的方法是遍历并处理找到的每个匹配项。这是一个来自 Java 的示例:

   import java.util.regex.*;

public class RepeatingCaptureGroupsDemo {
public static void main(String[] args) {
String input = "I have a cat, but I like my dog better.";

Pattern p = Pattern.compile("(mouse|cat|dog|wolf|bear|human)");
Matcher m = p.matcher(input);

while (m.find()) {
System.out.println(m.group());
}
}
}

输出:

cat
dog

(从 http://ocpsoft.org/opensource/guide-to-regular-expressions-in-java-part-1/ 开始,大约下降了 1/4)


请考虑为 Stack Overflow Regular Expressions FAQ 添加书签备查。此答案中的链接来自它。

关于Python re.finditer match.groups() 不包含匹配的所有组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23062143/

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