How to match String with Pattern in Groovy

2019-05-18 11:11发布

问题:

I am trying to decide whether a simple regular expression matches a string in Groovy. Here's my task in gradle. I tried to match with 2 different ways I found on the net, but neither of them works. It always prints out "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"
    }
}

回答1:

(?s) ignores line breaks for .* (DOTALL) and the regexp there means a full match. so with ==~ as shortcut it's:

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


回答2:

if (errorPattern.matcher(stdoutStr).matches()) {

The matches() method requires the whole string to match the pattern, if you want to look for matching substrings use find() instead (or just if(errorPattern.matcher(stdoutStr)) since Groovy coerces a Matcher to Boolean by calling find).