如何在 Groovy 中将字符串与模式匹配

How to match String with Pattern in Groovy

我正在尝试确定一个简单的正则表达式是否与 Groovy 中的字符串相匹配。这是我在 gradle 中的任务。我尝试匹配我在网上找到的 2 种不同方式,但它们都不起作用。它总是打印出 "NO ERROR FOUND"

task aaa << {
    String stdoutStr = "bla bla errors found:\nhehe Aborting now\n hehe"
    println stdoutStr
    Pattern errorPattern = ~/error/
//  if (errorPattern.matcher(stdoutStr).matches()) {
    if (stdoutStr.matches(errorPattern)) {
        println "ERROR FOUND"
        throw new GradleException("Error in propel: " + stdoutStr)
    } else {
        println "NO ERROR FOUND"
    }
}

(?s) 忽略 .* (DOTALL) 的换行符,那里的正则表达式表示完全匹配。所以用 ==~ 作为快捷方式是:

if ("bla bla errors found:\nhehe Aborting now\n hehe" ==~ /(?s).*errors.*/) ...
if (errorPattern.matcher(stdoutStr).matches()) {

matches() 方法要求整个字符串匹配模式,如果你想查找匹配的子字符串,请改用 find()(或者只是 if(errorPattern.matcher(stdoutStr)),因为 Groovy通过调用 find).

将 Matcher 强制转换为 Boolean