gpt4 book ai didi

Python正则表达式匹配给定字符串中的多个模式

转载 作者:太空宇宙 更新时间:2023-11-03 23:59:20 25 4
gpt4 key购买 nike

在下面的字符串中,我需要 Version: Build Number:perforce_url: 的值目前,我正在分别获取上面列出的每个匹配项。我想简化我的代码以在一行中获得匹配项。

x = '''Version: 2.2.4125
Build Number: 125
Project Name: xyz.master
Git Url: git+ssh://git@stash.xyz.com:123/ab/dashboard
Git Branch: origin/master
Git Built Data: qw123ed45rfgt689090gjlllb
perforce_url:
//projects/f5/dashboard/1.3/xyz/portal/
artifacts:
"..//www/": www/ '''

我已经使用 re.match 分别提取 Version: Build Number: 和 perforce_url: 的值。但是,我想简化并在一行中完成它。

import re
matchObj=re.match('Version:\s*(.*)\n', x)
if matchObj:
print matchObj.group(1)

matchObj=re.match('perforce_url:\s*(.*)\n', x)
if matchObj:
print matchObj.group(1)
matchObj=re.match('Build Number:\s*(.*)\n', x)
if matchObj:
print matchObj.group(1)

我尝试了以下模式:

版本:\s*(.*)\n|perforce_url:\s*(.*)\n.

但是没有用。我想创建一个列表 x 并将匹配项附加到列表中使用

list = []
list.append()

预期结果:

['2.2.4125', '//projects/f5/dashboard/1.3/xyz/portal/' , '125']

实际结果

2.2.4125

//projects/f5/dashboard/1.3/xyz/portal/

125

最佳答案

您可以将 Version 和 Build Number 放在一起,以便在捕获组中获取这些值。

对于 preforce_url 你可以使用一个重复模式,使用负前瞻 (?:\n(?!perforce).*)* 来匹配行,只要它们不开始使用 perforce_url。

当是时,然后使用捕获组匹配它:

Version:\s*(.*)\nBuild Number:\s*(.*)(?:\n(?!perforce).*)*\nperforce_url:\s*(.*)

Regex demo | Python demo

例如:

import re

regex = r"Version:\s*(.*)\nBuild Number:\s*(.*)(?:\n(?!perforce).*)*\nperforce_url:\s*(.*)"
x = ("Version: 2.2.4125\n"
"Build Number: 125\n"
"Project Name: xyz.master\n"
"Git Url: git+ssh://git@stash.xyz.com:123/ab/dashboard\n"
"Git Branch: origin/master\n"
"Git Built Data: qw123ed45rfgt689090gjlllb\n"
"perforce_url:\n"
" //projects/f5/dashboard/1.3/xyz/portal/\n"
"artifacts:\n"
" \"..//www/\": www/ ")

print(re.findall(regex, x))

结果

[('2.2.4125', '125', '//projects/f5/dashboard/1.3/xyz/portal/')]

关于Python正则表达式匹配给定字符串中的多个模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56263371/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com