pagid
pagid

Reputation: 13867

Indent multiline string with Groovy onliner

I'd like to indent a multiline string in Groovy but I can't figure out the right RegEx syntax / or Regex flags to achieve that.

Here's what I tried so far:

def s="""This
is
multiline
"""
println s.replaceAll('/(.*)/',"      \1")
println s.replaceAll('/^/',"     ")
println s.replaceAll('(?m)/^/',"      \1")
println s.replaceAll('(?m)/(.*)/',"      \1")

These didn't work as expected for some reason.

The only thing that worked so for is this block:

def indented = ""
s.eachLine {
  indented = indented + "      " +  it + "\n"
}
println indented

Is there a shorter / more efficient way to indent all lines of a string in Groovy?

Upvotes: 5

Views: 3569

Answers (3)

glenn jackman
glenn jackman

Reputation: 246799

You need to put the (?m) directive inside the regular expression; and the pattern is a slashy string, not a single quoted string with slashes inside:

s.replaceAll(/(?m)^/, "    ")

Upvotes: 5

Matias Bjarland
Matias Bjarland

Reputation: 4482

Or perhaps using just the replace function from java which is non-regex and potentially faster:

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

println '    ' + s.replace('\n', '\n    ')

which prints:

    This
    is
    multiline

note: for those who are picky enough, replace does use the java regex implementation (as in Pattern), but a LITERAL regex which means that it will ignore all normal regex escapes etc. So the above is probably still faster than split for large strings, but this makes you wish they had left some function in there that just did a replace without any involvement of the potentially slow Pattern implementation.

Upvotes: 1

baao
baao

Reputation: 73231

You could split and join - don't know if it's more efficient, but shorter

def s="""This
is
multiline
"""
def indent = "      "
println indent + s.split("\\n").join("\n" + indent);

Upvotes: 2

Related Questions