如何在正则表达式中找到模式?

时间:2019-07-03 02:58:37

标签: python regex

我想找到一种模式,并用另一个模式替换 假设我有:

"Name":"hello"

并且想要这样做

Name= "hello"

使用python正则表达式 该字符串可以是双引号内的任何内容,因此我需要找到模式“ ”:“ ”并将其替换为 =“

3 个答案:

答案 0 :(得分:5)

此表达式

^"\s*([^"]+?)\s*"\s*:\s*"?([^"]+)"?$

有两个捕获组:

([^"]+?) 

用于收集我们所需的数据。然后,我们只需re.sub

如果您感兴趣,请在此demo中对表达式进行说明。

测试

import re

result = re.sub('^"\s*([^"]+?)\s*"\s*:\s*"?([^"]+)"?$', '\\1= "\\2"', '"  Name  ":"  hello   "')
print(result)

答案 1 :(得分:3)

为什么不使用此正则表达式:

import re
s = '"Name":"hello"'
print(re.sub('"(.*)":"(.*)"', '\\1= \"\\2\"', s))

输出:

Name= "hello"

说明here

对于包含不止一种此类字符串的字符串,您需要向其中添加一些python代码:

import re
s = '"Name":"hello", "Name2":"hello2"'
print(re.sub('"(.*?)":"(.*?)"', '\\1= \"\\2\"', s))

输出:

Name= "hello", Name2= "hello2"

答案 2 :(得分:1)

使用纯Python,就像简单一样:

s = '"Name":"hello"'

print(s.replace(':', '= ').replace('"', '', 2))
# Name= "hello"