在Python中用group(2)替换group(1)

时间:2016-03-13 06:08:15

标签: python regex

我有这样的内容:

foreach ($_SESSION['arr'] as $item) {
    echo $item;
}

需要替换

[xxx]...[a]
[xxx]...[c]
[xxx]...[b]

我的代码在这里

[a]...[a]
[c]...[c]
[b]...[b]

输出

p = re.compile(ur'\[(.*?)\].*?\[(.*?)\]', re.MULTILINE)
test_str = u"[xxx]...[a]\n[xxx]...[c]\n[xxx]...[b]"

m = re.findall(p, test_str)
print m

我们如何用组(2)替换组(1)

[(u'xxx', u'a'), (u'xxx', u'c'), (u'xxx', u'b')]

2 个答案:

答案 0 :(得分:0)

请使用re.sub()替换正则表达式,findall()仅用于搜索:

In [14]: print p.sub(r'[\2]...[\2]', test_str)
[a]...[a]
[c]...[c]
[b]...[b]

答案 1 :(得分:0)

我认为...是其他文字的占位符。

test_str = u"[xxx]...[a]\n[xxx]...[c]\n[xxx]...[b]"
test_str2 = u"[xxx]abc1234[a]\n[xxx]xxx[c]\n[xxx]___[b]"

import re

def fixit(test):
    list1=test.split()
    list2=[]
    for st in list1:
        a=re.findall('\[\w\]',st)[0]
        list2.append(re.sub('\[xxx\]',a,st))  # re.sub(pattern, replacement, string)
    return '\n'.join(list2)

print fixit(test_str)
print
print fixit(test_str2)

输出:

[a]...[a]
[c]...[c]
[b]...[b]

[a]abc1234[a]
[c]xxx[c]
[b]___[b]