python - 我可以在一个 python 正则表达式查询中使用多个搜索条件来返回一个元组吗?

标签 python regex tuples

我有一个日志文件,当程序在不同的日子运行时,它会附加新日志。每次迭代都会有一个新的产品版本和启动开关。我需要每次迭代中的 Product Version: [0-9-]*Launch Switch:\w* 作为一个元组。

目前我正在这样做:

ver = re.findall(r'(?<=Product Version: )[0-9.]*', s)

launch = re.findall(r'(?<=Launch Switch: )\w*', s)

然后我将遍历 verlaunch 来创建元组。它可以工作,但它并不漂亮,我相信有一种更 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/

相关文章:

c# - 如何将函数参数列表转换为元组

python - GridSearch sklearn 上的参数感知评分函数

python - os.linesep 是干什么用的?

python - 对于格式错误的 python 代码,sed 中的 camelCase 到 snake_case

php - XPATH 检查属性是否包含多个值之一

javascript - 在 Javascript 中使用正则表达式从字符串中删除子字符串

python - 将元组添加到列表中而不让它们获得引号?

arrays - Swift 3 对元组数组进行排序

python - 形状文件输出

python - 如何使用 youtube_dl 和 FFMpegPCM 音频播放来自 youtube 的直播流? Discord.py 重写