我有一个日志文件,当程序在不同的日子运行时,它会附加新日志。每次迭代都会有一个新的产品版本和启动开关。我需要每次迭代中的 Product Version: [0-9-]*
和 Launch Switch:\w*
作为一个元组。
目前我正在这样做:
ver = re.findall(r'(?<=Product Version: )[0-9.]*', s)
launch = re.findall(r'(?<=Launch Switch: )\w*', s)
然后我将遍历 ver
和 launch
来创建元组。它可以工作,但它并不漂亮,我相信有一种更 Pythonic 的方法可以做到这一点。
最佳答案
您可以在正则表达式模式中使用多个捕获组; re.findall
然后将它们作为元组返回。例如:
>>> data = "Product Version: 0.0.1 | Launch Switch: hello | Product Version: 2.3.4 | Launch Switch: world"
>>> re.findall("Product Version: ([0-9.]+).*?Launch Switch: (\w+)", data)
[('0.0.1', 'hello'), ('2.3.4', 'world')]
来自 the re.findall
docs :
Return all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found. If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result unless they touch the beginning of another match.
关于python - 我可以在一个 python 正则表达式查询中使用多个搜索条件来返回一个元组吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14756984/