Close

Groovy Operators - Regular Expression Operators

[Last Updated: Dec 6, 2018]

Groovy provides following operators for working with regular expression:

Operator Description Example Equivalent Regex API
Pattern operator ~
To create java.util.regex.Pattern object.
def p = ~"a.*d"
def p = ~'a.*d'
def p = ~/a.*d/
All groovy's string quotes are allowed.
Pattern p = Patter.compile("a.*d")
Find Operator =~
To create java.util.regex.Matcher object.
def m = "awaked" =~  /a.*d/
Pattern p = Pattern.compile("a.*d");
Matcher m = p.matcher("awaked");
Match operator ==~
Calls matches#matches() method.
def b = "awaked" ==~ /a.*d/
Pattern p = Pattern.compile("a.*d");
Matcher m = p.matcher("awaked");
boolean b = m.matches();

Examples

Using Pattern operator ~

src/Example1PatternOperator.groovy

def pattern = ~"e.+?s"
println pattern.getClass()
def matcher = pattern.matcher("aggressiveness")
while (matcher.find()) {
    printf "match: %s, start: %s end: %s%n",
            matcher.group(), matcher.start(), matcher.end()
}

Output

class java.util.regex.Pattern
match: ess, start: 4 end: 7
match: enes, start: 9 end: 13

Using Find operator =~

src/Example2FindOperator.groovy

def matcher = "aggressiveness" =~ "e.+?s"
while (matcher.find()) {
    printf "match: %s, start: %s end: %s%n",
            matcher.group(), matcher.start(), matcher.end()
}

Output

match: ess, start: 4 end: 7
match: enes, start: 9 end: 13

Using Match operator ==~

def match = "aggressiveness" ==~ ".*ess.*"
println match

Output

true

Example Project

Dependencies and Technologies Used:

  • Groovy 2.5.3
  • JDK 9.0.1
Regular Expression Operators Select All Download
  • groovy-regular-expression-operators
    • src
      • Example2FindOperator.groovy

    See Also