【问题标题】:Jenkins and Groovy and RegexJenkins、Groovy 和正则表达式
【发布时间】:2016-12-21 14:08:37
【问题描述】:

我对使用 groovy 很陌生。尤其是 Jenkins+Groovy+Pipelines。

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

在我的 groovy 代码中:

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 循环,以使用此处的正则表达式信息和不同帖子 (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/
            }());

【问题讨论】:

  • 我最终取出了 'assert' 行,只是做 'r =~ /running|starting|stopped/' 感谢@injecteer

标签: jenkins groovy


【解决方案1】:

直截了当:

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

【讨论】:

  • 无论是否找到匹配,assert 是否总是返回 TRUE?
  • assert 永远不应在生产代码中返回。它通常在开始时用于检查先决条件
  • 对是否存在匹配采取行动的最佳方法是什么(例如进入然后中断一个while循环)?
  • 你要么做好javas breakreturn,要么使用常规收集方法,如find()grep()
  • @Karthi 请参阅 eachMatch() delineneo.com/2011/01/…
【解决方案2】:

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

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" 

解释:

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

==~ 运算符是常规的 binary match operator。如果匹配则返回true,否则返回false

在正则表达式 101 上查看 this example

【讨论】:

  • 感谢您的详尽解释和链接。最后,使用 '=~' 而不是 '==~' 以我想要使用此代码的方式为我工作
  • 在您的情况下,结果是相同的。然而,‘=~’ 将返回一个正则表达式对象,当没有匹配时为 nullassert null 将断言。因此它也会起作用。由于您没有使用该对象,因此您不一定需要该对象。一个布尔值就足够了。不知道性能和内存差异,尽管在这种情况下它们会非常小。 ==~ 将在第一场比赛中返回 true,因此在最坏的情况下将花费相同的时间。
  • 但很高兴它有所帮助。如果您想验证正则表达式,Regex101 是一个很棒的网站
  • 很好的解释!你拯救了我的一天。谢谢。
【解决方案3】:

matches 没有收到字符串。

试试

Pattern.compile("your-regex").matcher("string-to-check").find()

【讨论】:

  • 这确实需要明确的批准。否则会失败:org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: Scripts not allowed to use method java.util.regex.Matcher find
猜你喜欢
  • 1970-01-01
  • 2014-10-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-11
  • 1970-01-01
相关资源
最近更新 更多