Search code examples
regexgroovy

using regular expressions in groovy


I don't understand how I should use regular expressions in groovy despite it having several operators to work with it.

import java.util.regex.*

def line = "Line with 1 digits"

Pattern p = Pattern.compile("\\d+")
Matcher m = p.matcher(line)
if (m.find()) { // true
    println "found digit"
} else {
    println "not found digit"
}

if (line ==~ /\\d+/) { // false
    println "found"
} else {
    println "not found"
}

if (line =~ /\\d+/) { // false
    println "found"
} else {
    println "not found"
}

In my example in java code it found that there is a digit in the string successfully. However in groovy it was not able to do it.

What is wrong?


Solution

  • See this slashy string reference:

    Slashy strings are particularly useful for defining regular expressions and patterns, as there is no need to escape backslashes.

    You need to use a single backslash with \d in /\d+/ Groovy slashy strings defining a regex.

    if (line =~ /\d+/) { // false
        println "found"
    } else {
        println "not found"
    }
    

    The line =~ /\d+/ checks if a line contains one or more digits.

    The line2 ==~ /\d+/ checks if the whole string consists of only digits.

    See IDEONE demo.

    Also, see some more information about using regex in Groovy at regular-expressions.info.