Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using regular expressions in groovy

Tags:

regex

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?

like image 871
lapots Avatar asked Sep 15 '25 08:09

lapots


2 Answers

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.

like image 148
Wiktor Stribiżew Avatar answered Sep 17 '25 02:09

Wiktor Stribiżew


You can use find

if (line.find(/\d+/)) {
    println "found"
} else {
    println "not found"
}
like image 42
tim_yates Avatar answered Sep 17 '25 01:09

tim_yates