首页 文章

使用正则表达式用双引号字符串替换字符串

提问于
浏览
1

我想用 (double quotes + string) 替换一个字符串 . 需要将它用于python .

Input{responseHeader:{status:0,QTime:94}}

Output{"responseHeader":{"status":0,"QTime":94}}

尝试 /[^\d\W]+/g regex 得到 only string 但不知道 replace 如何用 (double quotes + string) .

2 回答

  • 2

    试试这个

    >>> import re
    >>> inp = '{responseHeader:{status:0,QTime:94}}'
    >>> re.sub(r'([a-zA-Z]+)',r'"\1"',inp)
    '{"responseHeader":{"status":0,"QTime":94}}'
    
  • 2
    ([a-zA-Z]+)
    

    试试这个 . 放置 "\1" . 参见演示 .

    https://regex101.com/r/sJ9gM7/18#python

    import re
    p = re.compile(r'([a-zA-Z]+)', re.MULTILINE)
    test_str = "{responseHeader:{status:0,QTime:94}}"
    subst = "\"\1\""
    
    result = re.sub(p, subst, test_str)
    

相关问题