Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strip indent in Groovy multiline strings

Tags:

groovy

Unfortunately stripIndent on a multiline string does not work. Side note: My IDE code style preferences allow only space indentation (tabs will be replaced by spaces). But I think this should have no matter.

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

does not print

This is multiline 

as expected.

The output is with indentation.

This                 is                multiline 

What is going wrong here?

I use Groovy 2.0.7 with Eclipse Indigo SR2.

The problem seems to disappear with the use of the backslash \ (String continuation character) in first line. But I don't understand why this is a must.

like image 366
Cengiz Avatar asked Nov 09 '13 20:11

Cengiz


People also ask

How do I remove spaces from a string in Groovy?

You can use the replaceAll() function. where \s means any whitespace (such as a space character).

How do you indent a multiline string in Python?

An alternative to using triple quotes ( ''' ) to create a multiline string is to enclose the entire string in brackets ( () ) and split our string using the enter button. This will automatically indent each line correctly as everything within the brackets is be considered one block of code.

What is stripMargin in Scala?

stripMargin ( '#' ) All of these approaches yield the same result, a multiline string with each line of the string left justified: Four score and seven years ago. This results in a true multiline string, with a hidden \n character after the word “and” in the first line.


1 Answers

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 """ 
like image 72
stefanglase Avatar answered Sep 21 '22 18:09

stefanglase