当前位置: 动力学知识库 > 问答 > 编程问答 >

Jenkins and Groovy and Regex

问题描述:

I am very new to using groovy. Especially when it comes to Jenkins+Groovy+Pipelines.

I have a string variable that can change from time to time and want to apply a regex to accomodate the 2 or 3 possible results the string may return.

In my groovy code I have:

r = "Some text that will always end in either running, stopped, starting."

def regex = ~/(.*)running(.*)/

assert regex.matches(r)

But I receive an error in the jenkins output:

hudson.remoting.ProxyException: groovy.lang.MissingMethodException: No signature of method: java.util.regex.Pattern.matches() is applicable for argument types: (java.lang.String)

UPDATE:

I was able to create a pretty nifty jenking groovy while loop in a pipeline job i am creating to wait for a remote process using the regex info here and a tip in a different post (do .. while() in Groovy with inputStream?).

 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/

}());

网友答案:

Straight-forward would be:

String r = "Some text that will always end in either running, stopped, starting."
assert r =~ /(.*)running(.*)/
网友答案:

matches does not receive String.

Try

Pattern.compile("your-regex").matcher("string-to-check").find()
网友答案:

If you are only using this regex here you can try the following:

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" 

Explanation:

(.*) - 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

the ==~ operator is the groovy binary match operator. This will return true if it matches, else false

See this example on regex 101

分享给朋友:
您可能感兴趣的文章:
随机阅读: