3

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"
    }
}
Gavriel
  • 18,880
  • 12
  • 68
  • 105
  • 2
    Doesn't `String.contains` suffice? – Will Jan 07 '15 at 11:18
  • In my real code I use a regular expression like: /(?i)error|fail|abort/, I'm not sure if contains works with Patters. If it does, then it would be a good solution – Gavriel Jan 07 '15 at 11:33
  • Nah, i thought it was just the `error` case :-) – Will Jan 07 '15 at 12:57
  • Agree the sample code didn't make clear OP wanted to use the matched substring data. I also like `String.startsWith()`. – MarkHu Feb 08 '17 at 01:04

2 Answers2

9

(?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.*/) ...
cfrick
  • 35,203
  • 6
  • 56
  • 68
3
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).

Ian Roberts
  • 120,891
  • 16
  • 170
  • 183