Home » Groovy » Check if String Contains a Substring in Groovy

Check if String Contains a Substring in Groovy

To check if a string contains a substring in Groovy, you can use the contains() method. Here's an example:

Check if String Contains a String in Groovy Examples

This code checks if the string str contains the substring "world". If it does, it prints "str contains 'world'". If it does not, it prints "str does not contain 'world'".

def str = "Hello world"
if (str.contains("world")) {
  println "str contains 'world'"
} else {
  println "str does not contain 'world'"
}

Here's another example that shows how to check if a string contains a substring in a case-insensitive manner:

def str = "Hello world"
if (str.toLowerCase().contains("world".toLowerCase())) {
  println "str contains 'world' (case-insensitive)"
} else {
  println "str does not contain 'world' (case-insensitive)"
}

In this code, we convert both the string and the substring to lowercase using the toLowerCase() method. This allows us to check if the string contains the substring without considering the case of the characters. If the string contains the substring, it prints "str contains 'world' (case-insensitive)". If it does not, it prints "str does not contain 'world' (case-insensitive)".

Related:

  1. Check if File Exists in Groovy
  2. Check if String is Empty in Groovy