Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - Matcher Object



When we use =~ operator to match a regular expression and a match is found, then it returns Matcher object.

Syntax

def regexDigits = "\\d+"
def text = "12243"

def matcher = text =~ regexDigits

The matcher object provides multiple useful methods to work with the matched string.

  • find() − find() method helps in searching the next match in the string. In case, match is found, it returns true else false is returned.

  • group() or [0] − It returns the matched substring.

  • group(n) or [n] − It is used to get the matched substring of nth capturing group.

  • start() − start() method gives the start index of the matched string.

  • end() − end() method returns the end index of matched string.

  • replaceAll(replacement) − This method is replace all the matched occurences of pattern with the replacement string passed.

  • replaceFirst(replacement) − This method is replace the first matched occurences of pattern with the replacement string passed.

Example - Searching all matches

We can use matcher.find() to search all occurences of a string.

Example.groovy

def text = "Order numbers: ORD-12345, ORD-67890"
def orderRegex = /(ORD-\d+)/

def matcher = text =~ orderRegex

// find all matches
while (matcher.find()) {
   println "Found order: ${matcher.group(1)} at index ${matcher.start()}"
}

Output

When we run the above program, we will get the following result.

Found order: ORD-12345 at index 15
Found order: ORD-67890 at index 26

Example - Replacing all matches

We can use matcher.replaceAll() to search and replace all occurences of a string.

Example.groovy

def text = "Order numbers: ORD-12345, ORD-67890"
def orderRegex = /ORD/

def matcher = text =~ orderRegex

def replacedText = text.replaceAll(orderRegex, 'ORDER-ID')
println "Updated text: ${replacedText}"

Output

When we run the above program, we will get the following result.

Updated text: Order numbers: ORDER-ID-12345, ORDER-ID-67890
Advertisements