什么是groovy中正确的正则表达式模式

时间:2017-07-24 22:03:29

标签: groovy jenkins-pipeline

在时髦的正则表达式中不是那么强大。我正在尝试在groovy中创建一个匹配器,用于字符串[sf:retrieve] Request ID for the current retrieve task: 09Sg00000052ZAPEA2

:之后的最后一部分,即09Sg00000052ZAPEA2是唯一不断变化的部分。如果字符串可用,我如何才能获得09Sg00000052ZAPEA2部分?

这是我到目前为止所尝试的:

import hudson.model.*
def parser() {
    def matcher = manager.getLogMatcher(".*Request ID for the*.*")
    if (matcher.matches()) {
        pbn=matcher.group(matcher.groupCount())
        return pbn
    }
}

该方法不会抛出任何错误,也不会返回任何内容

2 个答案:

答案 0 :(得分:1)

您可以使用.*:\\s(\\w+)作为模式并获取组中的第一个匹配项(我已经使用java.util.regex.Pattern进行了测试),我想您使用的lib将执行相同的操作方式:

String s = "[sf:retrieve] Request ID for the current retrieve task: 09Sg00000052ZAPEA2";
Pattern pattern = Pattern.compile(".*:\\s(\\w+)");
Matcher matcher = pattern.matcher(s);
if (matcher.matches()) {
    System.out.println(matcher.group(1));
}

答案 1 :(得分:0)

你的一些例子是jenkins特有的,我没有那个可用于测试,所以这个答案是古老的。但是,这相当于我相信你会想要的:

​String toMatch = "[sf:retrieve] Request ID for the current retrieve task: 09Sg00000052ZAPEA2"

def finder = (toMatch =~ /.*Request ID for the current retrieve task:(.*)/)
println finder.matches()
println finder.group(1)

基本上,将您想要的部分放回括号中。根据Java正则表达式语法,这使它成为编号组。然后,您可以使用模式匹配器获取该组值(如果匹配)。仅供参考,第0组是完全匹配的字符串(对于整个正则表达式),所以你从1开始计数,假设你不想要完整的东西。

当我运行这个例子时,我得到输出:

true
09Sg00000052ZAPEA2
相关问题