Groovy String.translateEscapes
Interpret Java escape sequences stored as literal characters in a string.
A simple example
String.translateEscapes
- Start with A, backslash, n, B
- Do this Interpret the escape
- Result A and B on two lines
Syntax
public String translateEscapes()
Run these examples in Groovy
Save one example at a time as Lesson.groovy. Use Groovy 4 on JDK 21.
groovy Lesson.groovyRead a saved line-break marker
A saved template contains escape markers that represent formatting instructions. Decode the stored markers once so the printed timetable has real tabs or line breaks at the intended positions.
String saved = 'A\\nB'
println saved.translateEscapes().lines().count()
2
The literal backslash sequence becomes a line break.
Decode a saved tab marker
A settings file stores a tab as a literal backslash and letter. Decode the marker and make the resulting tab visible in the output to verify which characters survived the conversion.
String saved = 'A\\tB'
println saved.translateEscapes().replace('\t', '|')
A|B
The template now has a real column separator.
Decode an address template
A mailroom stores the street and town in a one-line template. The stored template contains the two printable characters backslash and n. After decoding them as a newline, how many lines does the printer see?
What to watch for
This is Java escape syntax. Invalid escapes raise IllegalArgumentException and backslash-u Unicode escapes are not translated by this method.