python 匹配正则表达式返回组(如果存在)或为每个缺失组返回“无”

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 匹配正则表达式返回组(如果存在)或为每个缺失组返回“无”相关的知识,希望对你有一定的参考价值。

import collections
import re
import sys

STRING = basestring if sys.version_info.major < 3 else str


def get_group(match_, group_id):
    try:
        return match_[group_id]
    except IndexError:
        pass


def match(regex, text, groups=0):
    result = regex.search(text)
    if result:
        is_sequence = not isinstance(groups, STRING) and collections.Sequence
        return ([get_group(i) for i in groups] if is_sequence
                else get_group(groups))

以上是关于python 匹配正则表达式返回组(如果存在)或为每个缺失组返回“无”的主要内容,如果未能解决你的问题,请参考以下文章

Python正则表达式及常用匹配

Python正则表达式及常用匹配

Python常用的正则表达式处理函数详解

python中的正则表达式中的 ""

42 python中正则中的分组 正则中匹配字符串的起始和结尾以及单词边界

python正则子组匹配