抑制Python正则表达式中的匹配组

时间:2013-05-23 21:08:48

标签: python regex

我有以下代码来匹配转义字符串:

match_str = r'''(["/']).*?(?<!\\)(\\\\)*\1'''
test_str = r'''"This is an \"escaped\" string" and this isn't.'''

mo = re.match(match_str, test_str)

if mo:
    print mo.group()

工作正常。

然而,虽然我知道我需要那里的小组来处理重复等,但我对比赛后使用小组不感兴趣。我知道我可以调用mo.group(0)来获取整个事情,但是对于我正在做的事情,如果它可以表现得像在这种情况下没有找到任何组,即mo.groups()将返回(None)

有没有办法做到这一点?

编辑:如果有帮助,我正在尝试这样做:

ma = [myclass("regex1nogroups", [func1]),
      myclass("regex2twogroups", [func2, func3]),
      myclass("regex3fourgroups", [func4, func5, func6, func7]),
      myclass("regex4nogroups", [func8])]

for mc in ma:
    mo = re.match(mc.pattern, str_to_match)
    if mo:
        for n in range(len(mc.funclist)):
            result = mo.group(n+1 if mo.groups() else 0)
            mc.funclist[n](result)

使用函数列表的长度来确定正则表达式应该生成多少个组。如果我想假设没有组,我可以向myclass添加一个额外的标志成员为真,但是避免这种情况会很好。

2 个答案:

答案 0 :(得分:3)

只需添加?:即可获得非捕获组:

(?:\\\\)

答案 1 :(得分:0)

我最后只是以不同的方式处理问题,并采取明显的步骤来查看函数列表的长度,而不是查看re.groups()

ma = [myclass("regex1nogroups", [func1]),
      myclass("regex2twogroups", [func2, func3]),
      myclass("regex3fourgroups", [func4, func5, func6, func7]),
      myclass("regex4nogroups", [func8])]

for mc in ma:
    mo = re.match(mc.pattern, str_to_match)
    if mo:
        for n,f in enumerate(mc.funclist):
            result = mo.group(n+1 if len(mc.funclist) > 1 else 0)
            f(result)