如何使用RegEx提取Jenkins构建原因的有效内容?
Jenkins构建原因短描述提取的正则方案
需求说明
从Jenkins的currentBuild.getBuildCauses()[0].shortDescription获取的构建原因字符串中,提取以Started by开头的核心原因部分,去除后续冗余内容(如示例中by Bla bla bla这类附加信息)。
正则表达式方案
使用以下正则表达式即可精准匹配核心原因:
^Started by.*?(?= by |$)
正则逻辑解释
^:锚定字符串开头,确保从Started by开始匹配Started by:匹配固定起始标识.*?:非贪婪模式匹配任意字符,避免过度匹配(?= by |$):正向预查,匹配到第二个by或字符串结尾时停止,且不包含该停止部分
Jenkins Groovy代码示例
在Jenkins Pipeline中可以这样使用:
// 获取原始构建原因 def rawCause = currentBuild.getBuildCauses()[0].shortDescription // 应用正则提取核心原因 def matcher = rawCause =~ /^Started by.*?(?= by |$)/ // 处理匹配结果,若匹配失败则保留原始内容 def cleanCause = matcher.matches() ? matcher[0] : rawCause // 输出结果 echo "清理后的构建原因:${cleanCause}"
验证示例
- 输入:
Started by user by Bla bla bla→ 输出:Started by user - 输入:
Started by an upstream project by bla bla→ 输出:Started by an upstream project - 输入:
Started by a commit by more needless information→ 输出:Started by a commit
内容的提问来源于stack exchange,提问作者WhoAmI
相关产品推荐
相关产品推荐

