
彻底实现效果,请一杯咖啡(红包),聊表谢意。
... abc.js: actual output: { "loc": { "start": { "line": 1, }, "end": { "line": 1, } } } Error: xxxx abc.js: actual error: ... abc.js 不是固定内容(可能有 xxx.js 等),
abc.js 的数量不止一对,
actual output 和 actual error 是固定存在内容的有且仅有一对。
保留 abc.js 信息。
需要匹配多组
1 Leon406 2023-10-27 20:44:46 +08:00 |
2 Nile20 2023-10-27 21:11:49 +08:00 只保留了 xxx.js (分组的 group1 ) ^(\w+\.js): actual (?:output|error): \{.*?^\}$ https://imgur.com/mlj8UeY.png 推荐一个站点 https://regex101.com/ 可以实时预览正则效果(上图),记不住的 token 有速查,不熟悉的还可以让 GPT 帮你写,然后丢进来验证 |
3 nyxsonsleep OP @Leon406 ``` input_text="input_text.txt" output_text="output_text.txt" import re def change(): with open(input_text) as f: ss=f.readlines() s=''.join(ss) pattern = re.compile(r'([^.\s]+\.js): actual output: (.*?)\1: actual error') rs=re.findall(pattern,s) with open(output_text,'w') as fw: for i in rs : print(i[0]) fw.write(i[1]) # print(i[1]) print(len(rs)) change() ``` 匹配结果 0 个。 |
4 Leon406 2023-10-27 21:22:53 +08:00 |
5 nyxsonsleep OP @Leon406 匹配结果还是 0 |
6 nyxsonsleep OP @Nile20 需要 python 版本的。试过 GPT ,人工智障。 |
7 Leon406 2023-10-27 22:15:52 +08:00 @nyxsonsleep #5 发下测试数据, 我测试正常匹配三条数据 |
8 Nile20 2023-10-27 22:19:58 +08:00 @nyxsonsleep 我看你样例文本是.js 所以选的 js 。不同语言的正则库有一些差异,但是在你这个例子上并没有,只不过 python 里多行文本需要传递指定的 flags 给正则表达式 https://imgur.com/UYk3x8B.png |
9 Nile20 2023-10-27 22:21:31 +08:00 import re PATTERN = re.compile(r'^(\w+\.js): actual (?:output|error): \{.*?^\}$', flags=re.MULTILINE | re.DOTALL) txt = '''abc.js: actual output: { "loc": { "start": { "line": 1, }, "end": { "line": 1, } } } Error: xxxx abd.js: actual error: { "loc": { "start": { "line": 1, }, "end": { "line": 1, } } }''' match_ls = PATTERN.findall(txt) for m in match_ls: print(m) |
10 Nile20 2023-10-27 22:22:19 +08:00 python 强制用缩进来表示代码级别是我一直的槽点()。这下全乱了 |