简体   繁体   English

python替换中的正则表达式

[英]Regular expression in python replace

Is there any way using regular expression in python to replace all the occurrences of , (comma) after the flower braces { 是否有使用Python的正则表达式替换所有的出现的任何方式,花括号后(逗号) {

Data is of the following format in a file - abc.json 文件中的数据具有以下格式abc.json

{
"Key1":"value1",
"Key2":"value2"
},

{
"Key1":"value3",
"Key2":"value4"
},

{
"Key1":"value5",
"Key2":"value6"
}

This should result in following - 这应该导致以下情况-

{
"Key1":"value1",
"Key2":"value2"
}

{
"Key1":"value3",
"Key2":"value4"
}

{
"Key1":"value5",
"Key2":"value6"
}

As you can see the , (comma) has been removed after every braces } . 如您所见, ()在每个花括号之后都被除去了}

Would be helpful if this can be achieved via jq as well, apart from python REGEX 如果除了python regex之外,也可以通过jq实现这一点,将很有帮助

Test Source: https://regex101.com/r/wT6uU2/1 测试来源: https//regex101.com/r/wT6uU2/1

import re
p = re.compile(ur'},')
test_str = u"{\n\"Key1\":\"value1\",\n\"Key2\":\"value2\"\n},\n\n{\n\"Key1\":\"value3\",\n\"Key2\":\"value4\"\n},\n\n{\n\"Key1\":\"value5\",\n\"Key2\":\"value6\"\n}"

re.findall(p, test_str)

But use replace instead 但是使用替换代替

replace }, -> } 替换},->}

This works: 这有效:

import re

s="""{
"Key1":"value1",
"Key2":"value2"
},

{
"Key1":"value3",
"Key2":"value4"
},

{
"Key1":"value5",
"Key2":"value6"
}"""

pattern=re.compile(r'(?P<data>{.*?}),', re.S)

print pattern.findall(s)

s1=pattern.sub(r'\g<data>', s)
print s1

If you intend to process the resulting JSON in jq, it's probably easier to wrap it in brackets [{...}, {...}] to make it a JSON array. 如果您打算在jq中处理生成的JSON,可能更容易将其包装在括号[{...}, {...}]以使其成为JSON数组。 Then, you can use .[] in jq to unwrap the array. 然后,可以在jq中使用.[]解开数组。

Before you even consider other options, you really should go back to the source that generated that file and make sure it actually outputs valid json. 甚至在考虑其他选项之前,您实际上应该回到生成该文件的源,并确保它实际上输出有效的 json。

That said, you could use JQ to manipulate the contents as a raw string to add brackets, then parse it as an array to them spit out the contents. 就是说,您可以使用JQ将内容作为原始字符串来处理以添加方括号,然后将其解析为数组以吐出内容。

$ jq -Rs '"[\(.)]" | fromjson[]' abc.json

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM