Python 正则表达式 : How to extract string between parentheses and quotes if they exist

标签 python regex

我试图提取 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/

相关文章:

python - SQLAlchemy + MySQL 加入奇怪的行为

javascript - 如何测试字符串是否包含无效的字符串文字?

javascript - JavaScript Regex捕获十进制的重复部分

Python:链接的关键字

python - 展开字典的快捷方式

python - 如何在Python中使用递归

python - Pandas DataFrame 中的舍入条目

python - 如何使用雪球的加泰罗尼亚语词干分析器?

java - 正则表达式在运算符之后拆分数学表达式并查找负数

javascript - 获取两个 <a> 标签之间的字符串值