我有以下正则表达式:
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
re.sub
的repl
参数,如果是可调用的,应该接受一个匹配对象并返回一个字符串来替换原始字符串中的该匹配项。你的匹配包含了同一字符串的多个部分,因此不适合这种用法——尝试只捕获你想要替换的部分。 - jonrsharpe