Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 38 ยท Language Basics

Strings and GStrings in Groovy

Master Groovy strings: single, double, triple and slashy quotes, GString interpolation with $ and ${}, lazy evaluation, useful GDK methods, indexing, and regex operators.

Strings are where Groovy saves you the most typing. You get several kinds of quotes, built-in interpolation of variables and expressions, multi-line text, and a long list of extra string methods. You also get one famous trap, the difference between String and GString, which this lesson explains plainly.

Groovy blocks are read-only here. Runnable Java stand-ins show the same string operations with Java's APIs.

Five ways to write a string

GROOVY
def a = 'single quotes'                 // plain java.lang.String, no interpolation
def b = "double quotes, name: ${'x'}"   // GString when it contains ${...} or $name
def c = '''triple single
spans lines'''                          // multi-line, no interpolation
def d = """triple double
spans lines and interpolates ${1 + 1}"""
def e = /slashy strings need few escapes: \d+/
Syntax Multi-line Interpolation Typical use
'...' No No Everyday constant text
"..." No Yes Text with values
'''...''' Yes No Long text, SQL
"""...""" Yes Yes Templates, reports
/.../ Yes Yes Regular expressions
$/ ... /$ Yes Yes Dollar-slashy, regex with slashes

A single character is a String of length 1. Write 'a' as char or (char) 'a' when a real char is needed.

Interpolation

Inside a double-quoted string, $name inserts a variable and ${expression} inserts any expression:

GROOVY
def name = 'Ada'
def age = 36
println "Hello, $name!"                    // Hello, Ada!
println "Next year: ${age + 1}"            // Next year: 37
println "Name length: ${name.length()}"    // Name length: 3

The short form $name can follow a property path: "$person.name" means person.name, but it does not include method calls, so use the braces form for those. In "$name.length()" Groovy reads name.length as a property path and then the () as plain text, which is usually not what you want. Write "${name.length()}".

To print a literal dollar sign in a double-quoted string, escape it: "\$5".

The Java stand-in below imitates interpolation using formatted, which fills %s placeholders.

Java Java stand-in: building strings from values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

String versus GString

An interpolated double-quoted string is a GString (groovy.lang.GString), not a java.lang.String. Groovy converts it to a String automatically whenever a String is needed (method arguments, assignment to a String variable). This is invisible nearly always, but there is one well-known trap: map keys.

GROOVY
def key = 'a'
def map = ["$key": 1]        // the key is a GString
println map['a']             // null: the GString key has a different hash code than the String 'a'

A GString and a String with the same text are == equal, but their hashCode() values differ, so hash-based lookups can fail. Convert with .toString() or use single quotes for keys. Later, when you learn about maps, remember this rule: do not use GStrings as keys.

Lazy evaluation

A GString normally captures values when it is created, but a closure placeholder ${-> ...} is evaluated each time the GString is turned into text:

GROOVY
def n = 1
def eager = "n = $n"
def lazy = "n = ${-> n}"
n = 2
println eager     // n = 1
println lazy      // n = 2

Working with strings: the GDK

Groovy adds convenient operations on top of Java's String:

GROOVY
def s = 'Groovy'
println s.length()            // 6
println s[0]                  // G
println s[-1]                 // y     (last character)
println s[1..3]               // roo   (substring by range)
println s * 2                 // GroovyGroovy
println s + ' rocks'          // Groovy rocks
println 'a-b-c' - '-'         // ab-c  (removes the first match)
println s.toUpperCase()       // GROOVY
println s.reverse()           // yvoorG
println s.contains('oov')     // true
println 'abc'.padLeft(5, '*') // **abc
println 'abc'.center(7, '-')  // --abc--
println 'one two  three'.tokenize()   // [one, two, three]
println 'a,b,,c'.split(',')           // an array with 4 elements, including an empty one

Other frequently used methods: capitalize(), trim(), startsWith(), endsWith(), replace(), replaceAll(), count('o'), isBlank() and eachLine {}. Reading s[i] returns a one-character String; check the length first so an index outside the string does not surprise you.

tokenize() skips empty parts and treats its argument as a set of delimiter characters, while split() uses a regular expression and keeps empty parts. That difference trips up many scripts.

Java Java stand-in: indexing, ranges and repeat

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Multi-line text and stripIndent

Triple-quoted strings keep indentation. Use stripIndent() to remove the common leading spaces, or stripMargin() to cut up to a | marker:

GROOVY
def text = '''\
    Dear user,
      welcome!
    '''.stripIndent()

A backslash right after the opening quotes avoids a leading blank line.

Regular expressions

Groovy has operators for regexes, and the slashy string means you rarely need double backslashes:

GROOVY
assert 'order-1234' =~ /\d+/             // find: true if a match exists
assert 'abc123' ==~ /[a-z]+\d+/          // match: whole string must match
def m = 'id=42; id=77' =~ /id=(\d+)/
println m[0][1]                          // 42
println m.collect { it[1] }              // [42, 77]
println 'a1b22'.replaceAll(/\d+/, '#')   // a#b#
  • =~ creates a Matcher; used in a condition it means "find".
  • ==~ requires the whole string to match.
  • ~/pattern/ creates a Pattern object.

Groups are read by index: m[0] is the first match as a list, m[0][1] its first capture group.

Character escapes

Standard escapes work in non-slashy strings: \n, \t, \\, \', \", and Unicode รฉ. Slashy strings treat \ literally except for \/.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which string literal supports $name interpolation?

    Only double-quoted strings (and triple double quotes, slashy and dollar-slashy strings) interpolate. Single-quoted strings are literal.
  2. 2. What is the main danger of using a GString as a map key?

    GString and String with equal text are ==, but hash codes differ. Convert the key to String first.
  3. 3. What does 'Groovy'[-1] return?

    Negative indexes count from the end, so -1 is the last character.
  4. 4. Which operator requires the WHOLE string to match a pattern?

    ==~ returns true only if the entire string matches. =~ finds a match anywhere.
  5. 5. What does "${-> n}" do differently from "$n"?

    A closure placeholder is evaluated lazily, so changes to n after the GString was created are reflected.

Summary

  • Use single quotes for plain text, double quotes for interpolation, triple quotes for multi-line text and slashes for regexes.
  • $name and ${expr} insert values; use braces for method calls.
  • A GString is not a String: convert before using it as a map key.
  • The GDK adds indexing with ranges, *, -, tokenize, padLeft, center, and more.
  • =~, ==~ and ~/.../ give concise regular expressions.

Next: Operators