How to match a string to a pattern in Groovy
I'm trying to work out if a simple regex matches a string in Groovy. Here's my task in gradle. I tried to match two different ways that I found on the net, but neither works. It always prints "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"
}
}
+3
source to share
2 answers
if (errorPattern.matcher(stdoutStr).matches()) {
The method matches()
requires the entire string to match the pattern, if you want to find matching substrings, use instead find()
(or just if(errorPattern.matcher(stdoutStr))
, since Groovy forces Matcher to be Boolean by calling find
).
+3
source to share