我正在运行一个简单的正则表达式搜索两个条件Profile
和BuildDate
。我想涵盖这样一种可能性,即我要么同时找到两个结果,要么一个结果,或者没有结果,并返回尽可能多的信息。以下是我的写作方式,但我想知道是否还有更像Python的方式?
p = re.search(r'Profilet+(w+)',s)
d = re.search(r'BuildDatet+([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))
p = re.search(r'Profilet+(w+)',s)
d = re.search(r'BuildDatet+([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))
它不那么冗长,但有点晦涩。