Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save alswl/6ff13e68f10e7800636891f44af7b78d to your computer and use it in GitHub Desktop.
Save alswl/6ff13e68f10e7800636891f44af7b78d to your computer and use it in GitHub Desktop.
python convert_named_group_to_position_based_group
# coding=utf-8
from __future__ import print_function, unicode_literals
import re
def convert_named_group_to_position_based_group(regex, replacement):
position_based_regex = regex
position_based_replacement = replacement
named_groups = [x[3:-1] for x in re.findall(r'(\?P<[a-z_]+>)', regex)]
named_group_dict = dict(zip(named_groups, range(1, len(named_groups) + 1)))
for name in named_groups:
position_based_regex = position_based_regex.replace('?P<{}>'.format(name), '')
position_based_replacement = position_based_replacement.replace(
'${{{}}}'.format(name), '${{{}}}'.format(named_group_dict[name]))
return position_based_regex, position_based_replacement
@alswl
Copy link
Author

alswl commented May 16, 2016

由来:

七牛和阿里云的文件存储系统,在做图片处理时候,需要将自有 URL 规则映射对方规则。
使用正则进行映射,但是双方系统的正则都只支持基于顺序的 group,而不支持 named group。

使用 named group 的优势在于语义,所以在内部规则生成器上面,我使用 named group,而提供给对方的规则,使用 index based group。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment