首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >regex替换regex

regex替换regex
EN

Stack Overflow用户
提问于 2013-03-17 03:44:59
回答 2查看 218关注 0票数 2

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

代码语言:javascript
复制
x1 = re.compile('''((?P<unicode>u?)(?P<c1>'|")(?P<data>.+?)(?P<c2>'|"))''')

我想提取这个正则表达式的datac1c2部分,以生成一个替换字符串(如果是c1 == c2)

类似于:

代码语言:javascript
复制
repl = "u<c1><data><c2>"

我该怎么做??

这在一行中是可行的还是通过使用re.sub

更新

我的新代码:

代码语言:javascript
复制
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()])

在这里,我有问题来确定如何不改变评论中的字符串,我要做什么来忽略这些评论??

EN

回答 2

Stack Overflow用户

发布于 2013-03-17 04:17:57

假设你有一个模式:

代码语言:javascript
复制
pattern = r'''(?P<unicode>u?)(?P<c>'|")(?P<data>.*?)(?P=c)''' # did a little tweak

匹配字符串:

代码语言:javascript
复制
m = re.search(pattern, "print('hello')")

你得到了什么:

代码语言:javascript
复制
>>> m.groups()
('', '"', 'hello')
>>> m.groupdict()
{'c': '"', 'unicode': '', 'data': 'hello'}

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

代码语言:javascript
复制
>>> 'u{c}{data}{c}'.format_map(m.groupdict())
'u"hello"'

也许您正在使用Python2.x:

代码语言:javascript
复制
>>> 'u{c}{data}{c}'.format(**m.groupdict())
'u"hello"'

甚至连你都喜欢老%

代码语言:javascript
复制
>>> "u%(c)s%(data)s%(c)s" % m.groupdict()
'u"hello"'

编辑的

regex解决方案不能正确处理某些情况。

因此,我使用了一个2to3黑客(实际上是3到2,仍然不能解决所有问题):

代码语言:javascript
复制
cd /usr/lib/python3.3/lib2to3/fixes/
cp fix_unicode.py fix_unicode33.py

编辑fix_unicode33.py

代码语言:javascript
复制
-_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。这里的逻辑很简单,修改它以达到您的目标。

票数 1
EN

Stack Overflow用户

发布于 2013-03-18 04:46:49

我最后得到的长代码。

代码语言:javascript
复制
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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15457310

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档