Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - Defining Regular Expressions



We can define regular expression in groovy in multiple ways.

  • Using regular strings − We can use regular string as regular expression similar to Java.

  • Using slashy strings − Slashy strings are string surrounded by slash characters(/ /).

  • Using dollar slashy strings − Dollar slashy string are strings surrounded by dollar slashes ($/ $/).

Let's explore each ways to define regular expressions with examples −

Example - Using Strings as regular expression

We can use regular strings as a regular expression but we need to take care of escaping special characters.

Example.groovy

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

if (result) {
   println "Valid. Text contains digits only."
} else {
   println "Invalid Input. Only digits required."
}

text = "abc123"
result = text ==~ regexDigits

if (result) {
   println "Valid. Text contains digits only."
} else {
   println "Invalid Input. Only digits required."
}

Output

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

Valid. Text contains digits only.
Invalid Input. Only digits required.

Example - Using Slashy Strings as regular expression

We can use slashy strings as a regular expression as here we are not required to escape special characters.

Example.groovy

def regexDigits = /\d+/
def text = "12243"
def result = text ==~ regexDigits

if (result) {
   println "Valid. Text contains digits only."
} else {
   println "Invalid Input. Only digits required."
}

text = "abc123"
result = text ==~ regexDigits

if (result) {
   println "Valid. Text contains digits only."
} else {
   println "Invalid Input. Only digits required."
}

Output

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

Valid. Text contains digits only.
Invalid Input. Only digits required.

Example - Using Dollar Slashy Strings as regular expression

We use dollar slashy strings for complex regular expression as here we can use single quote, double quote without escaping.

Example.groovy

def regexHtml = $/<p class='info'>.*?</p>/$
def text = "<p class='info'>ABCD</p>"
def result = text =~ regexHtml

if (result) {
   println "Valid."
} else {
   println "Invalid html format."
}

text = "<ABCD></p>"
result = text =~ regexHtml

if (result) {
   println "Valid."
} else {
   println "Invalid html format."
}

Output

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

Valid.
Invalid html format.
Advertisements