[英]regex replace unable to substitute in Python with regex variables
我们有大量文件需要转换为 json 这是一个文件的示例数据
{
1=2,
4=tt,
6=9
}
{
1=gg,
2=bd,
6=bb
}
我正在使用 python 转换正则表达式工作正常的数据,但是当我在 python 代码中实现时,相同的正则表达式不起作用
import numpy as np
f = open('/Users/rahulvarma/Downloads/2020120911.txt', 'r')
content = f.read()
import re
regex = r"([0-9]+)(=)((.*)+)"
subst = "\"$1\":\"$3\","
result = re.sub(regex, subst, content, 0, re.MULTILINE)
if result:
print (result)
但我是
{
"$1":"$3",
"$1":"$3",
"$1":"$3"
}
{
"$1":"$3",
"$1":"$3",
"$1":"$3"
}
我预期的 output 应该是
{
"1":"2",
"4":"tt",
"6":"9"
}
{
"1":"gg",
"2":"bd",
"6":"bb"
}
您可以使用此正则表达式进行搜索:
(\d+)=([^,\n]*)(,|$)
并替换使用:
"\1":"\2"\3
代码:
regex = r"(\d+)=([^,\n]*)(,|$)"
result = re.sub(regex, r'"\1":"\2"\3', input_str, 0, re.MULTILINE)
正则表达式详细信息:
(\d+)
:匹配捕获组#1 中的 1+ 个数字=
: 匹配=
字符([^,\n]*)
: 匹配 0 个或多个不是,
而不是\n
在捕获组 #2 中的任何字符(,|$)
: 匹配捕获组 #3 中的逗号或行尾
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.