Groovy String.stripIndent
Remove common incidental indentation from a multiline string while preserving relative indentation.
A simple example
String.stripIndent
- Start with Two spaces then A, two spaces then B
- Do this Remove common leading indent
- Result Lines A and B
Syntax
public String stripIndent()
Run these examples in Groovy
Save one example at a time as Lesson.groovy. Use Groovy 4 on JDK 21.
groovy Lesson.groovyAlign a pasted report
A report copied from an editor arrives with indentation on every line. Remove the common margin for publication while leaving the second-level headings visibly indented.
String report = " North\n Gate"
println report.stripIndent(false).replace("\n", "|")
North| Gate
The common margin is removed and the relative indent remains.
Clean a badge template
A user pastes a multi-line block from a formatted document into a plain-text field. Remove the common outer margin while preserving meaningful differences between the lines inside it.
String label = " LAB \n A "
println label.stripIndent(false).replace("\n", "|")
LAB|A
Selecting the JDK behaviour also removes trailing whitespace.
Align an exhibit checklist
A curator pastes two indented lines from a planning document. The sample has the same two-space indentation on every nonempty line. Which first word appears when removing that common indentation?
What to watch for
A final line terminator influences the common indentation. This example supplies strings without a trailing newline.