【问题标题】:regex to replace regex正则表达式替换正则表达式
【发布时间】:2013-03-17 03:44:59
【问题描述】:

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

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

我想提取此正则表达式的datac1,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()])

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

【问题讨论】:

  • @MortenJensen 是的.. 但是如果您打算使用它来回答,请详细说明...
  • 我猜你想要的是让代码在 3.3 和 2.x 下工作。也许2to3是一个不错的选择。如果你不反对使用它,我会更新我的解决方案。
  • @Kabie 你好久没更新了,猜你在等我的OK...
  • 我在等你更新你的真实问题。

标签: python regex replace


【解决方案1】:

假设你有一个模式:

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。这里的逻辑很简单,修改一下就可以达到你的目的。

【讨论】:

  • 谢谢,但我正要发布一个编辑,关于如何更改我的功能(我将发布)以不编辑 cmets...
  • 我不明白你的编辑是什么意思.. 2to3/3to2 是什么??
  • @Schoolboy:这是为了回答另一个你没有问但我假设的问题 - 在 python 源文件中的字符串中添加 u 前缀。
【解决方案2】:

我最终得到的长代码。

x1 = re.compile('''(?P<unicode>u?)(?P<c>'|")(?P<data>.*?)(?P=c)''')

def in_string(text,index):
    curr,in_l,in_str,level = '',0,False,[]

    for c in text[:index+1]:
        if c == '"' or c == "'":
            if in_str and curr == c:
                instr = False
                curr = ''
                in_l -= 1
            else:
                instr = True
                curr = c
                in_l += 1
        level.append(in_l)
    return bool(level[index])

def repl(m):
    return "u%(c)s%(data)s%(c)s" % m.groupdict()

def handle_hashes(i):
    if i.count('#') == 1:
        n = i.find('#')
    else:
        n = get_hash_out_of_string(i)
    return re.sub(x1,repl,i[:n]) + i[n:]

def get_hash_out_of_string(i):
    n = i.find('#')
    curr = i[:]
    last = (len(i)-1)-''.join(list(reversed(i))).find('#')
    while in_string(curr,n) and n < last:
        curr = curr[:n]+' '+curr[n+1:]
        n = curr.find('#')
    return n

【讨论】:

    猜你喜欢
    • 2019-01-24
    • 2015-01-24
    • 1970-01-01
    • 2014-03-29
    • 2012-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多