我试图提取 Jenkinsfiles 中括号和引号之间的每个触发器的值/参数(如果存在)。
例如,给定以下内容:
upstream(upstreamProjects: 'upstreamJob', threshold: hudson.model.Result.SUCCESS) # just parentheses
pollSCM('H * * * *') # single quotes and parentheses
分别期望的结果:
upstreamProjects: 'upstreamJob', threshold: hudson.model.Result.SUCCESS
H * * * *
我当前的结果:
upstreamProjects: 'upstreamJob', threshold: hudson.model.Result.SUCCESS
H * * * *' # Notice the trailing single quote
到目前为止,我已经成功使用了第一个触发器(上游触发器),但没有成功使用第二个触发器(pollSCM),因为仍然有一个尾随单引号。
在组 (.+)
之后,它不会捕获带有 \'*
的尾随单引号,但它会捕获带有 的右括号\)
。我可以简单地使用 .replace() 或 .strip() 来删除它,但是我的正则表达式模式有什么问题?我该如何改进它?这是我的代码:
pattern = r"[A-Za-z]*\(\'*\"*(.+)\'*\"*\)"
text1 = r"upstream(upstreamProjects: 'upstreamJob', threshold: hudson.model.Result.SUCCESS)"
text2 = r"pollSCM('H * * * *')"
trigger_value1 = re.search(pattern, text1).group(1)
trigger_value2 = re.search(pattern, text2).group(1)
最佳答案
import re
s = """upstream(upstreamProjects: 'upstreamJob', threshold: hudson.model.Result.SUCCESS) # just parentheses
pollSCM('H * * * *')"""
print(re.findall("\((.*?)\)", s))
输出:
["upstreamProjects: 'upstreamJob', threshold: hudson.model.Result.SUCCESS", "'H * * * *'"]
关于Python 正则表达式 : How to extract string between parentheses and quotes if they exist,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50167232/