正则匹配,怎么匹配不定内容的成对的中间的内容呢?

195 天前
 nyxsonsleep

彻底实现效果,请一杯咖啡(红包),聊表谢意。

...
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 信息。

需要匹配多组

761 次点击
所在节点    正则表达式
10 条回复
Leon406
195 天前




([^.\s]+\.js): actual output: (.*?)\1: actual error

分组匹配 group1 是 js, group2 是中间内容
Nile20
195 天前
只保留了 xxx.js (分组的 group1 )
^(\w+\.js): actual (?:output|error): \{.*?^\}$

https://imgur.com/mlj8UeY.png

推荐一个站点 https://regex101.com/ 可以实时预览正则效果(上图),记不住的 token 有速查,不熟悉的还可以让 GPT 帮你写,然后丢进来验证
nyxsonsleep
195 天前
@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 个。
Leon406
195 天前
@nyxsonsleep #3
. 匹配换行
nyxsonsleep
195 天前
@Leon406 匹配结果还是 0
nyxsonsleep
195 天前
@Nile20 需要 python 版本的。试过 GPT ,人工智障。
Leon406
195 天前
@nyxsonsleep #5 发下测试数据, 我测试正常匹配三条数据
Nile20
195 天前
@nyxsonsleep 我看你样例文本是.js 所以选的 js 。不同语言的正则库有一些差异,但是在你这个例子上并没有,只不过 python 里多行文本需要传递指定的 flags 给正则表达式

https://imgur.com/UYk3x8B.png
Nile20
195 天前
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)
Nile20
195 天前
python 强制用缩进来表示代码级别是我一直的槽点╮(╯▽╰)╭。这下全乱了

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/986124

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX