Skip to main content
 首页 » 编程设计

python之正则表达式替换正则表达式

2025年05月04日26hnrainll

我有这个用于在 Python 代码中获取字符串的正则表达式:

x1 = re.compile('''((?P<unicode>u?)(?P<c1>'|")(?P<data>.+?)(?P<c2>'|"))''') 

我想提取此正则表达式的 data 和 c1,c2 部分来生成替换字符串(如果 c1 = = c2)
像这样的东西:

repl = "u<c1><data><c2>" 

我该怎么做?
这可能在一行中或通过使用 re.sub 实现吗?

更新:
我的新代码:

x1 = re.compile('''(?P<unicode>u?)(?P<c>'|")(?P<data>.*?)(?P=c)''') 
def repl(match): 
    if '#' in match.string: 
        ### Confused 
    return "u%(c)s%(data)s%(c)s" % m.groupdict() 
 
fcode = '\n'.join([re.sub(x1,repl,i) for i in scode.splitlines()]) 

在这里,我在确定如何不更改评论中的字符串时遇到问题,我该怎么做才能忽略评论?

请您参考如下方法:

假设你有一个模式:

pattern = r'''(?P<unicode>u?)(?P<c>'|")(?P<data>.*?)(?P=c)''' # did a little tweak 

匹配一个字符串:

m = re.search(pattern, "print('hello')") 

你得到了什么:

>>> m.groups() 
('', '"', 'hello') 
>>> m.groupdict() 
{'c': '"', 'unicode': '', 'data': 'hello'} 

现在你可以用这些做任何你想做的事了:

>>> 'u{c}{data}{c}'.format_map(m.groupdict()) 
'u"hello"' 

也许您正在使用 Python 2.x:

>>> 'u{c}{data}{c}'.format(**m.groupdict()) 
'u"hello"' 

或者甚至你喜欢旧的 %

>>> "u%(c)s%(data)s%(c)s" % m.groupdict() 
'u"hello"' 

已编辑:

正则表达式解决方案无法正确处理某些情况。

所以我用了一个2to3 hack(实际上是3to2,还是不能解决所有问题):

cd /usr/lib/python3.3/lib2to3/fixes/ 
cp fix_unicode.py fix_unicode33.py 

编辑fix_unicode33.py

-_literal_re = re.compile(r"[uU][rR]?[\'\"]") 
+_literal_re = re.compile(r"[rR]?[\'\"]") 
 
-class FixUnicode(fixer_base.BaseFix): 
+class FixUnicode33(fixer_base.BaseFix): 
 
-                new.value = new.value[1:] 
+                new.value = 'u' + new.value 

现在 2to3 --list | grep unicode33 应该输出 unicode33

然后你可以运行2to3 -f unicode33 py3files.py。

记得在

之后删除 fix_unicode33.py

注意:在 Python3 中 ur"string" 抛出 SyntaxError。这里的逻辑很简单,修改它以达到你的目标。