Skip to content

Groovy & Java Regex Match and Find

Groovy provides some operators to have an efficient way to create pattern, find or test regex compared with Java.

Here are some common use case in Groovy and Java,

  • create a pattern

In Groovy,

Groovy
Pattern pattern = ~/regex/
With Java,
Java
Pattern pattern = Pattern.compile(regex)

  • find with Regex

In Groovy,

Groovy
Matcher matcher = "string" =~ /regex/
if (matcher.find()) {
    def str = matcher.group(1)
}
With Java,
Java
Pattern pattern = Pattern.compile("pattern");
Matcher matcher = pattern.matcher("string");
if (matcher.find()) {
    var str = matcher.group(1);
}
* test with Regex

In Groovy,

Groovy
def match = "string" ==~ /regex/
With Java,
Java
var match = "string".matches("regex");
or
Java
var match = Pattern.matches("regex", "string");