如何解析jenkins控制台的输出,返回值并保存在变量中

oxcyiej7  于 2022-11-02  发布在  Jenkins
关注(0)|答案(1)|浏览(232)

我在解析jenkins管道控制台输出时遇到了问题。每次我传递一个作业时,控制台中都会出现一行:

12:29:08 [10:29:07] NIDD version is: SBTS23R1_NIDD_2217_100_01

我想从中提取一个变量值:SBTS23R1_NIDD_2217_100_01并将其保存在变量中,以便我可以进一步使用它。
我试着做了一些像这里所描述的那样的事情:GROOVY: Finding a string from console output if a regexp string found
不幸的是,我得到的错误:

an exception which occurred:
    in field com.cloudbees.groovy.cps.impl.BlockScopeEnv.locals
    in object com.cloudbees.groovy.cps.impl.BlockScopeEnv@20cd216a
    in field com.cloudbees.groovy.cps.impl.CpsClosureDef.capture
    in object com.cloudbees.groovy.cps.impl.CpsClosureDef@3e3cd6ed
    in field com.cloudbees.groovy.cps.impl.CpsClosure.def
    in object org.jenkinsci.plugins.workflow.cps.CpsClosure2@6be3d3c7
    in field org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.closures
    in object org.jenkinsci.plugins.workflow.cps.CpsThreadGroup@14fde9cd
    in object org.jenkinsci.plugins.workflow.cps.CpsThreadGroup@14fde9cd
Caused: java.io.NotSerializableException: java.util.regex.Matcher

我的代码:

def matcher = ("12:29:08 [10:29:07] NIDD version is: SBTS23R1_NIDD_2217_100_01" =~ /NIDD version is:\SBTS\d{2}\w\d_NIDD_\d{4}_\d{3}_\d{2}/) 

if (matcher.hasGroup()) 
{ 
  def msg = matcher[0][1] println("Build failed because of ${msg}") 
}
xkftehaa

xkftehaa1#

您需要使用捕获组,并使用冒号和SBT之间的任意数量的空格(您错误地转义了S,使SBT中的S成为非空格匹配的速记字符类的一部分):

def matcher = ("12:29:08 [10:29:07] NIDD version is: SBTS23R1_NIDD_2217_100_01" =~ /NIDD version is:\s*(SBTS\d{2}\w\d_NIDD_\d{4}_\d{3}_\d{2})/)
if (matcher) {
    def msg = matcher[0][1]
    println("Build failed because of ${msg}")
}

请参阅Groovy demo

相关问题