gpt4 book ai didi

python - 如何替换为正则表达式命名组?

转载 作者:太空宇宙 更新时间:2023-11-03 19:14:20 25 4
gpt4 key购买 nike

我试图根据 regex 在日志文件中查找匹配行,然后检查其中的组并报告预期行和实际行。以下示例显示了我到底想要做什么。

regex_str = '^.*name is (?P<name>[^.]*).*lives? in (?P<place>[^.]*).*$'
statement = 'My name is bala. I live in mumbai.'
statement2 = 'His name is bala. He lives in mumbai.'
ret = find_line([statement,'Garbage'],regex_str,name='bala',place='chennai')

ret == {
'Expected' : 'My name is bala. I live in chennai.'
'Actual' : 'My name is bala. I live in mumbai.'
'isMatched': False
}

ret = find_line([statement2,'Garbage'],regex_str,name='bala',place='chennai')

ret == {
'Expected' : 'His name is bala. He lives in chennai.'
'Actual' : 'His name is bala. He lives in mumbai.'
'isMatched': False
}

ret = find_line(['Garbage1','Garbage2'],regex_str,name='bala',place='chennai')

ret == {
'Expected' : '^.*name is (?P<name>[^.]*).*lives? in (?P<place>[^.]*).*$'
'Actual' : '<No matching line>'
'isMatched': False
}

ret = find_line(['Garbage1',statement,'Garbage2',statement2],regex_str,name='bala',place='mumbai')

ret == {
'Expected' : 'My name is bala. I live in mumbai.'
'Actual' : 'My name is bala. I live in mumbai.'
'isMatched': True
}

我真正的用例是第一个参数将是一个 file_object。 find_line 函数将继续跟踪文件,直到找到匹配项(正确或错误)或达到固定超时。

我正在寻找 find_line 的实现,它将提供所需的输出。有什么建议/解决方案吗?

最佳答案

我的简单尝试

import re
def find_line(lines,regex_str,**params):
regex = re.compile(regex_str)
for line in lines:
m = regex.match(line)
if m:
actual = m.string
groups = sorted (
[(0,0,'')] +
[(m.start(gname),m.end(gname),gname) for gname in params] +
[(len(actual),0,'')])
expected = ''
for i in range(len(groups)-1):
expected += actual[groups[i][1]:groups[i+1][0]]
gname = groups[i+1][2]
if gname: expected += params[gname]
return {'Expected': expected, 'Actual': actual, 'isMatched' : expected == actual}
return {'Expected': None, 'Actual': None, 'isMatched' : False}

如果找不到匹配项,则会出现问题(示例 3)。正如我们从示例中看到的,“预期”是转换数学字符串的结果。因此,如果没有对任何字符串进行数学运算,则无法形成预期值。

关于python - 如何替换为正则表达式命名组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11872084/

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