Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

strip indent in groovy multiline strings

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
"""

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...