詹金斯、Groovy 和正则表达式

Jua*_*anD 5 groovy jenkins

我对使用 groovy 很陌生。尤其是当涉及到 Jenkins+Groovy+Pipelines 时。

我有一个可以不时更改的字符串变量,并希望应用正则表达式来适应字符串可能返回的 2 或 3 个可能的结果。

在我的常规代码中,我有:

r = "Some text that will always end in either running, stopped, starting." def regex = ~/(.*)running(.*)/ assert regex.matches(r)

但是我在 jenkins 输出中收到一个错误:

hudson.remoting.ProxyException:groovy.lang.MissingMethodException:没有方法签名:java.util.regex.Pattern.matches() 适用于参数类型:(java.lang.String)

更新:我能够在我正在创建的管道作业中创建一个非常漂亮的 jenking groovy while 循环,以等待远程进程使用此处的正则表达式信息和不同帖子中的提示(在 Groovy 中使用 inputStream 执行 .. while() ?)。

            while({
                def r = sh returnStdout: true, script: 'ssh "Insert your remote ssh command that returns text'
                println "Process still running.  Waiting on Stop"
                println "Status returned: $r"
                r =~ /running|starting|partial/
            }());
Run Code Online (Sandbox Code Playgroud)

inj*_*eer 5

直接将是:

String r = "Some text that will always end in either running, stopped, starting."
assert r =~ /(.*)running(.*)/
Run Code Online (Sandbox Code Playgroud)


Rik*_*Rik 5

如果您仅在此处使用此正则表达式,您可以尝试以下操作:

r = "Some text that will always end in either running, stopped, starting."
assert r ==~ /(.*)(running|stopped|starting)\.?$/, "String should end with either running, started or stopped" 
Run Code Online (Sandbox Code Playgroud)

解释:

(.*) - matches anything
(running|stopped|starting) - matches either running, stopped or starting
\.? - optionally end with a dot expect zero or one occurrence of a dot, but you need to escape it, because the dot is a regex special character
$ - end of the line, so nothing should come after
Run Code Online (Sandbox Code Playgroud)

该==~运算符是常规的二进制匹配运算符。true如果匹配则返回,否则返回false

请参阅regex 101 上的示例