python正则表达式匹配并用引号替换转义字符

时间:2015-12-08 12:32:02

标签: python regex

给出一个字符串

test = '''my name\t is "zyb\org"'''; 

我想匹配双引号中出现的“\ o”字符,并将其替换为“o”。我正在努力以合适的方式去做。请帮忙。

我理解如何使用

匹配双引号
 "\"(.+)\""g

但编写嵌入式正则表达式以识别转义字符是我遇到问题的地方。

1 个答案:

答案 0 :(得分:0)

你可以选择:

".*(\\.).*"gim

其中:

"".*(\\.).*""gim

    " matches the characters " literally
    .* matches any character (except newline)
        Quantifier: * Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
    1st Capturing group (\\.)
        \\ matches the character \ literally
        . matches any character (except newline)
    .* matches any character (except newline)
        Quantifier: * Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
    " matches the characters " literally
    g modifier: global. All matches (don't return on first match)
    i modifier: insensitive. Case insensitive match (ignores case of [a-zA-Z])
    m modifier: multi-line. Causes ^ and $ to match the begin/end of each line (not only begin/end of string)

这里是 LiveDemo

这是一种方法:

import re
line = '''my name\t is "zyb\org"'''
replaced = re.sub(r'"(.*)\\(.*)"', r"\1\2", line)
print(replaced)