strip indent in groovy multiline strings

Use .stripMargin() as well (if feasible).

def s = """ This 
            | is
            | multiline
        """
println s.stripMargin().stripIndent()

stripMargin() is to strip leading spaces from lines with margin.

Default margin is |. We can also specify a custom margin.

For example,

def s = """*This 
        *is
            *multiline
"""

println(s.stripMargin("*"))

will result in

This 
is
multiline

The best practice is that we append .trim() in the end to eliminate leading and trailing spaces of the whole string.

For example,

println(s.stripMargin("*").trim())

You can use .stripIndent() to remove the indentation on multi-line strings. But you have to keep in mind that, if no amount of indentation is given, it will be automatically determined from the line containing the least number of leading spaces.

Given your string this would be only one white space in front of This which would be removed from every line of your multi-line string.

def s = """ This 
            is
            multiline
"""

To work around this problem you can escape the first line of the multi-line string as shown in the following example to get your expected result:

def s = """\
           This
           is
           multiline
"""

For anyone else having a similar problem, stefanglase's solution is great but is giving me a MultipleCompilationErrorsException in a Spock test when including a multiline String in an assertion that fails:

org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
Spec expression: 1: unexpected char: '\' @ line 1, column 16.
   myString == '''\ This Is Multiline '''.stripIndent()

My solution to this is:

def myString = '''
  This
  Is
  Multiline
  '''.replaceFirst("\n","").stripIndent()

Now, when the assertion fails, you will see the usual diff indicating what went wrong, rather than the compilation exception.

Tags:

Groovy