Python正则表达式从OR运算符的非匹配方返回None

时间:2018-03-03 23:23:42

标签: python regex

我试图创建一个正则表达式,它将从OR的任意一侧返回两个匹配,如下所示:

def parse_description(description):
    regex = r"^(Created by CreateImage\((.*?)\) for (.*?) |Copied for (DestinationAmi) (.*?) from SourceAmi (.*?))"
    matches = re.finditer(regex, description, re.MULTILINE)
    for matchNum, match in enumerate(matches):
        return match.groups()
    return '', ''

带有示例字符串:

Copied for DestinationAmi ami-33dfxxx from SourceAmi ami-9dd6xxx for SourceSnapshot snap-02f5xxx. Task created on 1,518,952,817,897.

我遇到的问题是这会返回4场比赛,无,无,ami-33dfxxx,ami-9dd6xxx

https://pythex.org/尝试了各种各样的事情我不能让这不能返回4场比赛,尽管据我所知,它不应该是。我做错了什么?

1 个答案:

答案 0 :(得分:0)

感谢建议分支重置的评论,这是我的最终解决方案

import regex
def parse_description(description):
    pattern = r'^(?|Created by CreateImage\((.*?)\) for (.*?) |Copied for (DestinationAmi) (.*?) from SourceAmi )'
    matches = regex.match(pattern,description)
    if matches is None:
        return None
    return(matches.groups())