Library contents

Groovy String.stripIndent

Remove common incidental indentation from a multiline string while preserving relative indentation.

A simple example

String.stripIndent

  1. Start with Two spaces then A, two spaces then B
  2. Do this Remove common leading indent
  3. Result Lines A and B
With no final blank line, both lines contribute two spaces to the common indent.

Syntax

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

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

From the programString report = " North\n Gate"
ResultNorth| Gate
Lesson.groovy
String report = "   North\n     Gate"
println report.stripIndent(false).replace("\n", "|")
Output
North|  Gate

The common margin is removed and the relative indent remains.

Advertisements

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.

From the programString label = " LAB \n A "
ResultLAB|A
Lesson.groovy
String label = "  LAB   \n  A "
println label.stripIndent(false).replace("\n", "|")
Output
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?

Given“ Mount” / “ Light”
Worked resultMount

What to watch for

A final line terminator influences the common indentation. This example supplies strings without a trailing newline.

Documentation for String.stripIndent