【问题标题】:Better way to return any match in a python regex search?在 python 正则表达式搜索中返回任何匹配项的更好方法?
【发布时间】:2013-02-22 17:52:58
【问题描述】:

我正在对ProfileBuildDate 两个条件进行简单的正则表达式搜索。 我想说明我会找到两个、一个或没有结果并返回尽可能多的信息的可能性。这是我的编写方式,但我想知道是否有更 Pythonic 的方式?

    p = re.search(r'Profile\t+(\w+)',s)
    d = re.search(r'BuildDate\t+([A-z0-9-]+)',s)

    # Return whatever you can find. 
    if p is None and d is None:
        return (None, None)
    elif p is None:
        return (None, d.group(1))
    elif d is None:
        return (p.group(1), None)
    else:
        return (p.group(1),d.group(1))

【问题讨论】:

    标签: python regex search


    【解决方案1】:
    p = re.search(r'Profile\t+(\w+)',s)
    d = re.search(r'BuildDate\t+([A-z0-9-]+)',s)
    
    return (p.group(1) if p is not None else None,
            d.group(1) if d is not None else None)
    

    也是这样:

    return (p and p.group(1), d and d.group(1))
    

    不那么冗长,但有点晦涩。

    【讨论】:

    • 非常优雅,正是我想要的。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-05
    • 2021-08-15
    相关资源
    最近更新 更多