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

2024-05-13 00:10:25 发布

您现在位置:Python中文网/ 问答频道 /正文

在下面的字符串中,我需要值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/ '''

我用过重新匹配分别提取Version:Build Number:和perforce\u 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


Tags: gitbuildreurlnumberifversionmatch
2条回答

根据第四只鸟的回答,但有点扭曲。 通过使用非捕获组,您可以避免在“Build Number”和“perforce”之间有一个非捕获组。这样,您就只需要为显式想要的目标设置regex。你知道吗

r"Version:\s*(.*)\n|Build Number:\s*(.*)\n|perforce_url:\s*(.*)\n"

regex

编辑:不需要围绕“版本”、“构建”等实现非捕获组

您可以将版本号和内部版本号放在后面,以便在捕获组中获取这些值。你知道吗

对于preforce\u url,您可以使用一个重复模式,并使用一个负的lookahead(?:\n(?!perforce).*)*来匹配行,只要它们不以perforce\u 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/')]

相关问题 更多 >