Groovy Guide — Strings: Interpolation and Advanced Features
In this tutorial, you will learn about Groovy Guide. We cover key concepts, practical examples, and best practices to help you master this topic.
Groovy extends Java strings with string interpolation (GStrings), multi-line strings, slashy strings for regex, and dozens of additional methods for flexible text processing.
What You'll Learn
- Single and double-quoted strings
- String interpolation with GStrings
- Multi-line strings
- Slashy strings and regex
- String method extensions
Why It Matters
String manipulation is universal. Groovy's extensions make common string tasks more concise and readable. Durga Antivirus Pro uses Groovy strings for log formatting and pattern matching.
Real-World Use
Template generation, log formatting, configuration processing, and text Parsing benefit from Groovy's string features.
flowchart LR
A["Strings"] --> B["GStrings"]
B --> C["Multi-line"]
C --> D["Slashy"]
D --> E["Methods"]
A:::current --> B
style A fill:#2563eb,stroke:#2563eb,color:#fff
style B fill:#dbeafe,stroke:#2563eb,color:#1e40af
style C fill:#dbeafe,stroke:#2563eb,color:#1e40af
style D fill:#dbeafe,stroke:#2563eb,color:#1e40af
style E fill:#f1f5f9,stroke:#94a3b8,color:#64748b
String Types
// Single-quoted (plain string)
def s1 = 'Hello World'
// Double-quoted (GString if interpolated)
def s2 = "Hello $name"
// Triple-quoted (multi-line)
def s3 = '''Line 1
Line 2
Line 3'''
// Slashy (regex)
def s4 = /hello.*world/
String Interpolation
def name = "Alice"
def age = 30
// Variable interpolation
println "Name: $name, Age: $age"
// Expression interpolation
println "Next year: ${age + 1}"
// Method call
println "Upper: ${name.toUpperCase()}"
// Property access
class Person { String name }
def p = new Person(name: "Bob")
println "Person: $p.name"
Multi-line Strings
// Triple single quotes (no interpolation)
def sql = '''
SELECT *
FROM users
WHERE age > 21
ORDER BY name
'''
// Triple double quotes (with interpolation)
def table = "users"
def query = """
SELECT *
FROM $table
WHERE active = true
"""
// Strip indent
def html = '''\
<html>
<body>
<h1>Title</h1>
</body>
</html>'''.stripIndent()
Slashy Strings
// No escaping needed for backslashes
def regex = /hello\s+world/
def text = "hello world"
println text ==~ regex // true
// Multi-line slashy
def multilineRegex = /
hello
\s+
world
/
// Dollar slashy (escaping $)
def template = $/The price is ${price} dollars/$
String Methods
def text = "Hello World, from Groovy!"
// Case
text.toUpperCase() // "HELLO WORLD, FROM GROOVY!"
text.toLowerCase() // "hello world, from groovy!"
text.capitalize() // "Hello World, from Groovy!"
// Padding
"5".padLeft(5, '0') // "00005"
"hello".center(11) // " hello "
// Tokenize
"a,b,c".split(',') // ["a", "b", "c"]
"a b c".tokenize() // ["a", "b", "c"]
Pattern Matching
def email = "alice@example.com"
// Find operator
println email =~ /^\w+@\w+\.\w+$/ // java.util.regex.Matcher
// Match operator
println email ==~ /^\w+@\w+\.\w+$/ // true
// Capture groups
def matcher = "Name: Alice, Age: 30" =~ /Name: (\w+), Age: (\d+)/
if (matcher) {
println matcher[0][1] // "Alice"
println matcher[0][2] // "30"
}
Common Mistakes
1. Performance of GStrings
GStrings are lazy. Converting toString or passing to methods that expect String forces evaluation.
2. Dollar sign in GStrings
Use ${} or escape with $. Slashy strings don't interpret $.
3. GString equality
GStrings don't equal plain strings. Use toString() before comparison with Java strings.
4. Multi-line indentation
.stripIndent() removes common leading whitespace. Use it for readable multi-line strings.
5. Regex escaping
Slashy strings reduce but don't eliminate escaping needs. Still escape special characters.
Practice Questions
1. What is a GString? A double-quoted string that supports variable interpolation with $ and ${} syntax.
2. How do you create a multi-line string? Use triple quotes: '''...''' or """...""" for multi-line strings.
3. What is a slashy string? A string delimited by / that reduces backslash escaping, commonly used for regex patterns.
Challenge: Write a Groovy script that parses log lines using regex with slashy strings.
FAQ
{{< faq question="Are GStrings efficient?" >} GStrings use lazy evaluation. For repeated interpolation, convert to String once with toString(). {{< /faq >}}
{{< faq question="How do I escape $ in GStrings?" >} Use ${dollar} or switch to single-quoted strings. Slashy and dollar-slashy strings handle this differently. {{< /faq >}}
{{< faq question="Can Groovy strings be null-safe?" >}
Yes, use the ?. operator: str?.toUpperCase() returns null instead of NPE.
{{< /faq >}}
{{< faq question="What does stripIndent do?" >} Removes common leading whitespace from multi-line strings, preserving relative indentation. {{< /faq >}}
{{< faq question="How is =~ different from ==~?" >} =~ creates a matcher (find). ==~ returns boolean (exact match). Use =~ for partial matches. {{< /faq >}}
Mini Project
Build a log parser with Groovy strings:
def logEntry = "2024-01-15 10:30:45 ERROR [main] Connection failed: timeout"
def pattern = /(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2}) (\w+) \[(\w+)\] (.+)/
def matcher = logEntry =~ pattern
if (matcher) {
def (_, date, time, level, thread, message) = matcher[0]
println "Date: $date"
println "Time: $time"
println "Level: $level"
println "Thread: $thread"
println "Message: $message"
}
What's Next
Now that you understand strings, explore Groovy's collection operations.
| Topic | Description | Link |
|---|---|---|
| Groovy Collections | Lists, maps, and ranges | {{< ref "06-collections" >}} |
| Groovy Control Flow | Control flow | {{< ref "07-control-flow" >}} |
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro