在正则表达式匹配中替换命名组

时间:2015-11-10 16:00:06

标签: python regex replace

我有以下正则表达式:

pattern = '^[a-zA-Z0-9-_]*_(?P<pos>[A-Z]\d\d)_T\d{4}(?P<fID>F\d{3})L\d{2}A\d{2}(?P<zID>Z\d{2})(?P<cID>C\d{2})\.tif$'

匹配文件名,如下所示:

filename = '151006_655866_Z01_T0001F015L01A02Z01C03.tif'

与小组:

m = re.match(pattern, filename)
print m.group("pos")  # Z01
print m.group("fID")  # F015
print m.group("zID")  # Z01

如何在Python中仅使用给定字符串替换指定的组?

我尝试将re.sub与函数调用一起使用,但不知道此函数的外观如何:

def replace_function(matchobj):
    # how to replace only a given match group?
    # (the following replaces *all* occurrences of "Z01" in this example)
    return matchobj.group(0).replace(matchobj.group("slice"), "---")

print re.sub(pattern, replace_function, filename)

我想要的结果是:

151006_655866_Z01_T0001F015L01A02---C03.tif

2 个答案:

答案 0 :(得分:3)

您可以使用闭包和所选匹配组的开始/结束索引来执行您需要的操作:

import re
from functools import partial

pattern = '^[\w-]*_(?P<pos>[A-Z]\d{2})_T\d{4}(?P<fID>F\d{3})L\d{2}A\d{2}(?P<zID>Z\d{2})(?P<cID>C\d{2})\.tif$'
filename = '151006_655866_Z01_T0001F015L01A02Z01C03.tif'


def replace_closure(subgroup, replacement, m):
    if m.group(subgroup) not in [None, '']:
        start = m.start(subgroup)
        end = m.end(subgroup)
        return m.group()[:start] + replacement + m.group()[end:]

subgroup_list = ['pos', 'fID', 'zID', 'cID']
replacement = '---'

for subgroup in subgroup_list:
    print re.sub(pattern, partial(replace_closure, subgroup, replacement), filename)

<强>输出

151006_655866_---_T0001F015L01A02Z01C03.tif
151006_655866_Z01_T0001---L01A02Z01C03.tif
151006_655866_Z01_T0001F015L01A02---C03.tif
151006_655866_Z01_T0001F015L01A02Z01---.tif

可以使用在线实施here

答案 1 :(得分:2)

要获得所需的输出,只需捕获要开始和结束的内容 保留。在它之间插入---

查找^([a-zA-Z0-9_-]*_[A-Z]\d\d_T\d{4}F\d{3}L\d{2}A\d{2})Z\d{2}(C\d{2}\.tif)$
替换:$1---$2