测试字符串:
s = '(x + 2 - y)'
所需:
'\(x \+ 2 - y\)'
我想从包含()+
的字符串中创建一个正则表达式。替换 pattern 需要转义那些,以便将结果用作正则表达式模式。可以使用三个str.replace
语句来完成,但是我被困在尝试使用单个re.sub
语句来完成。
以下works in online Python flavored regex testers,但不在我的Python shell中:
pattern = '(?P<char>[(+)])'
repl = '\\\g<char>'
>>> s = '(x + 2 - y)'
>>> pattern = '(?P<char>[(+)])'
>>> repl = '\\\g<char>'
>>>
>>> re.sub(pattern, repl, s)
'\\g<char>x \\g<char> 2 - y\\g<char>'
>>>
我尝试了使用多个反斜杠的各种组合并使用组号而不是组名的多种替换模式。
>>> repl = '\\\\g<char>'
>>> re.sub(pattern, repl, s)
'\\g<char>x \\g<char> 2 - y\\g<char>'
>>> repl = r'\\\\g<char>'
>>> re.sub(pattern, repl, s)
'\\\\g<char>x \\\\g<char> 2 - y\\\\g<char>'
>>> repl = r'\\g<char>'
>>> re.sub(pattern, repl, s)
'\\g<char>x \\g<char> 2 - y\\g<char>'
>>> repl = '\\\g<char>'
>>> re.sub(pattern, repl, s)
'\\g<char>x \\g<char> 2 - y\\g<char>'
>>> repl = '\\\1'
>>> re.sub(pattern, repl, s)
'\\\x01x \\\x01 2 - y\\\x01'
>>> repl = '\\\g<1>1'
>>> re.sub(pattern, repl, s)
'\\g<1>1x \\g<1>1 2 - y\\g<1>1'
是否有re.sub
替换模式可以做到这一点?