如何匹配正则表达式中的每行一个?

2024-04-26 13:07:31 发布

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

我创建的正则表达式有问题。 我的公司在错误文件中搜索错误,并尝试将该文件与一组可能的字符串相匹配。 如果找到其中一个字符串,则表示发生了特定错误,然后我们向客户端发送一封电子邮件,告诉他们发生了哪些错误,以及每个特定字符串集的计数

假设我有string

Number 123456789: Duplicate transaction detected
Number 543267890: is a duplicate for this vendor
Password error number 987654321
The total can not be negative

然后我将搜索所有“重复”错误、“密码”错误和“负面”错误。 每种类型的错误都有一组字符串,这些字符串可能表示该错误

我正在运行以下正则表达式以获取重复错误:

number_of_errors = re.subn(
    r"(is a duplicate for this vendor|Duplicate transaction detected)", "", string,
)[1]

number_of_errors变量保存在字符串中找到正则表达式的次数。 在执行错误处理的第三方软件开始以不同的方式创建文件之前,它一直工作正常

现在,该文件可能如下所示:

Number 123456789: Duplicate transaction detected because it is a duplicate for this vendor
Number 543267890: is a duplicate for this vendor
Password error number 987654321
The total can not be negative

如您所见,现在第一行将被计数两次,因为正则表达式匹配第一行中的两个字符串

有没有办法在正则表达式中每行只匹配一次

提前谢谢


Tags: 文件字符串numberforstringis错误this
3条回答

可以在re.subn函数中使用参数计数。这是为了指示要进行的最大替换次数

number_of_errors = re.subn(
    r"(is a duplicate for this vendor|Duplicate transaction detected)", "", string, count = 1)[1]

是的,使用

r"(?m)^.*?(is a duplicate for this vendor|Duplicate transaction detected)"

proof(?m)^.*?部分使模式在每行的开头匹配,因为插入符号匹配行的起始位置,.*?匹配除换行符以外的任何零个或多个字符,但尽可能少

如果您检查re.subn(pattern, repl, string, count=0, flags=0)的参数,您会看到有一个参数计数,您可以将其设置为1

相关问题 更多 >