正则表达式组的引用长度

iGw*_*wok 2 python regex python-2.7 python-3.x

我正在尝试用散列替换文件名末尾的数字,例如image.0010001.tiff将成为图像.#######.tiff

是否可以使用单个re.sub方法执行此操作?

这是我到目前为止:

re.sub('(\d+)(?=\.\w+$)', '#'*len('\g<1>'), 'image.0010001.tiff')
Run Code Online (Sandbox Code Playgroud)

Ara*_*Fey 6

您可以将函数传递给re.sub:

re.sub('(\d+)(?=\.\w+$)', lambda match:'#'*len(match.group(1)), 'image.0010001.tiff')
Run Code Online (Sandbox Code Playgroud)