Created
April 20, 2016 10:45
-
-
Save alswl/6ff13e68f10e7800636891f44af7b78d to your computer and use it in GitHub Desktop.
python convert_named_group_to_position_based_group
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
由来:
七牛和阿里云的文件存储系统,在做图片处理时候,需要将自有 URL 规则映射对方规则。
使用正则进行映射,但是双方系统的正则都只支持基于顺序的 group,而不支持 named group。
使用 named group 的优势在于语义,所以在内部规则生成器上面,我使用 named group,而提供给对方的规则,使用 index based group。