用单引号内的双引号替换单引号

时间:2016-07-23 20:06:51

标签: python regex

以下是我要找的内容:

curl -X POST -H "Content-type: application/json" -d '{"group":"stash-adt_ooms-dev","users":['stack', 'overflow']}' "url"

结果:

curl -X POST -H "Content-type: application/json" -d '{"group":"admin","users":["stack", "overflow"]}'

需要正则表达式将[]之间的单词从单引号替换为双引号。

3 个答案:

答案 0 :(得分:0)

您需要获取左括号和左括号的位置,然后将'替换为"。你可以这样做:

_str = """curl -X POST -H "Content-type: application/json" -d '{"group":"stash-adt_ooms-dev","users":['stack', 'overflow']}' "url" """

start = _str.find ("[")
end = _str.find ("]")
buff = _str[start:end].replace ("'", "\"")
_str = _str[:start] + buff + _str[end:]

希望这有帮助!

答案 1 :(得分:0)

使用re.sub内的lambda而不是替换字符串模式的正则表达式方法:

import re
s = """curl -X POST -H "Content-type: application/json" -d '{"group":"stash-adt_ooms-dev","users":['stack', 'overflow']}' "url" """
res = re.sub(r"\[.*?]", lambda x: x.group().replace("'", '"'), s)
print(res)
# => curl -X POST -H "Content-type: application/json" -d '{"group":"stash-adt_ooms-dev","users":["stack", "overflow"]}' "url" 

请参阅Python demo

\[.*?]正则表达式与文字[匹配,然后匹配除换行符之外的零个或多个字符(如果要匹配子字符串,请将flags=re.DOTALL添加到re.sub跨越多行),尽可能少,直到第一个]消耗。

lambda获取匹配数据对象x,并仅在匹配值'内替换".group(),即在内所有{{}输入字符串中的1}} substrings

答案 2 :(得分:0)

a = "curl -X POST -H \"Content-type: application/json\" -d '{\"group\":\"stash-adt_ooms-dev\",\"users\":['stack', 'overflow']}' \"url\""

b = re.sub(r'\[\'(\w+)\', \'(\w+)\'\]',r'["\1", "\2"]' , a)

打印b将导致以下内容:

'curl -X POST -H "Content-type: application/json" -d \'{"group":"stash-adt_ooms-dev","users":["stack", "overflow"]}\' "url"'