Jan*_*ger 6 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$'
Run Code Online (Sandbox Code Playgroud)
匹配如下文件名:
filename = '151006_655866_Z01_T0001F015L01A02Z01C03.tif'
Run Code Online (Sandbox Code Playgroud)
与团体:
m = re.match(pattern, filename)
print m.group("pos") # Z01
print m.group("fID") # F015
print m.group("zID") # Z01
Run Code Online (Sandbox Code Playgroud)
如何在 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)
Run Code Online (Sandbox Code Playgroud)
我想要的结果是:
151006_655866_Z01_T0001F015L01A02---C03.tif
Run Code Online (Sandbox Code Playgroud)
您可以使用闭包和所选匹配组的开始/结束索引来执行您需要的操作:
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)
Run Code Online (Sandbox Code Playgroud)
输出:
151006_655866_---_T0001F015L01A02Z01C03.tif
151006_655866_Z01_T0001---L01A02Z01C03.tif
151006_655866_Z01_T0001F015L01A02---C03.tif
151006_655866_Z01_T0001F015L01A02Z01---.tif
Run Code Online (Sandbox Code Playgroud)
此处提供在线实施
| 归档时间: |
|
| 查看次数: |
3682 次 |
| 最近记录: |