Strings in Groovy are sequences of characters and are used to represent textual data. Groovy provides a rich set of features for working with strings, including string interpolation, concatenation, and manipulation.
Creating Strings:
You can create strings in Groovy using either single quotes '' ''or double quotes '" "'. Double-quoted strings support string interpolation, while single-quoted strings are plain literals.
Example:
def name = "Alice"
def greeting = 'Hello,'
In this example, we created two strings, 'name' and 'greeting'.
String Interpolation:
String interpolation allows you to embed variables and expressions within double-quoted strings using '${}'.
Example:
def age = 30
def message = "My age is ${age}"
In this example, the 'message' string is created by interpolating the 'age' variable.
String Concatenation:
You can concatenate strings using the '+' operator or the 'concat()' method.
In this example, 'isEqual' will be set to 'false'.
Regular Expressions in Groovy
Regular expressions (regex) are powerful patterns used for searching, matching, and manipulating strings. Groovy supports regular expressions through the '=~' operator and various methods in the 'java.util.regex' package.
Pattern Matching:
You can use the '=~' operator to check if a string matches a regular expression pattern.
Example:
def text = "Hello, World!"
def pattern = /Hello,/
def isMatch = text =~ pattern
In this example, 'isMatch' will be set to 'true'because the pattern matches the string.
Pattern Searching:
The 'find()'method can be used to search for the first occurrence of a pattern in a string.
Example:
def text = "The quick brown fox jumps over the lazy dog."
def pattern = /brown/
def found = text.find(pattern)
In this example, 'found'will be set to '"brown"'.
Pattern Replacement:
You can use the 'replaceAll()' method to replace all occurrences of a pattern with a replacement string.
Example :
def text = "The quick brown fox jumps over the lazy dog."
def pattern = /brown/
def replaced = text.replaceAll(pattern, "red")
In this example, 'replaced' will be set to '"The quick red fox jumps over the lazy dog."'.
Capturing Groups:
Regular expressions can define capturing groups to extract specific parts of a matched string.
Example :
def text = "Date: 2023-09-01"
def pattern = /Date: (\d{4}-\d{2}-\d{2})/
def match = text =~ pattern
def date = match[0][1]
In this example, the date '"2023-09-01"' is extracted using a capturing group.
Conclusion:
Strings and regular expressions are essential tools for text manipulation and pattern matching in Groovy. Understanding how to create, manipulate, and search for strings, as well as how to use regular expressions, is crucial for working with textual data in Groovy applications. These features enable you to perform a wide range of text-processing tasks efficiently and effectively.