Library contents

Groovy String.translateEscapes

Interpret Java escape sequences stored as literal characters in a string.

A simple example

String.translateEscapes

  1. Start with A, backslash, n, B
  2. Do this Interpret the escape
  3. Result A and B on two lines
The two written characters backslash and n become one newline.

Syntax

Groovy 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.groovy

Read 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.

From the programString saved = 'A\\nB'
Result2
Lesson.groovy
String saved = 'A\\nB'
println saved.translateEscapes().lines().count()
Output
2

The literal backslash sequence becomes a line break.

Advertisements

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.

From the programString saved = 'A\\tB'
ResultA|B
Lesson.groovy
String saved = 'A\\tB'
println saved.translateEscapes().replace('\t', '|')
Output
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?

GivenPier\nYork
Worked result2

What to watch for

This is Java escape syntax. Invalid escapes raise IllegalArgumentException and backslash-u Unicode escapes are not translated by this method.

Documentation for String.translateEscapes