Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - Regex Tasks



Regular expression are very useful in deducing information from text. In this chapter, we're uncovering following useful tasks −

  • Extract Information − We can parse a text file to get useful information like timestamp, error details etc.

  • Validate Input − Using regular expression, we can validate user input as per required format easily.

  • Split Strings − We can split strings like entries of comma seperated values, csv files.

Example - Extract Information

In this example, we're extracting useful information from a log entry like date, time, log level and log message.

Example.groovy

def entryLog = "2025-05-10 18:09:00 INFO: User 'Julie' is working on accounts functionality."
def regexLog = /(\d{4}-\d{2}-\d{2})\s+(\d{2}:\d{2}:\d{2})\s+([A-Z]+):\s+(.*)/

// match regular expression
def matcher = entryLog =~ regexLog
matcher.matches()
println "Date: ${matcher.group(1)}"
println "Time: ${matcher.group(2)}"
println "Level: ${matcher.group(3)}"
println "Message: ${matcher.group(4)}"

Output

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

Date: 2025-05-10
Time: 18:09:00
Level: INFO
Message: User 'Julie' is working on accounts functionality.

Example - Validate Inputs

We can use regular expression to validate user inputs very easily and covering most of the cases as shown below −

Example.groovy

def validEmail = "test@tutorialspoint.com"
def invalidEmail = "test.example.com"
def regexEmailValidation = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/

println "$validEmail is validated as : ${validEmail ==~ regexEmailValidation}"
println "$invalidEmail is validated as: ${invalidEmail ==~ regexEmailValidation}"

Output

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

test@tutorialspoint.com is validated as : true
test.example.com is validated as: false

Example - Spliting Strings

We can use regular expression to split strings based on multiple separators as shown below −

Example.groovy

def data = "apple,banana;orange,grape;papaya"

def regexSeparator = /[,;]/

def fruits = data.split(regexSeparator)

println fruits 

Output

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

[apple, banana, orange, grape, papaya]
Advertisements