groovy 带'join(“\n”)'数组中插入字符串的多行字符串stripIndent()

kkbh8khc  于 2022-12-03  发布在  其他
关注(0)|答案(1)|浏览(135)

当我在多行字符串中使用.join("\n")数组的结果时,stripIndent()似乎不起作用:

def list = [ 'one', 'two' ]
def listAsString = list.join("\n")

def string = """\
  First line for listAsString

  $listAsString

  Last line
""".stripIndent()

注意:我使用转义的第一行。
这将产生:

First line for listAsString

  one
two

  Last line

代替

First line for listAsString

one
two

Last line
  • 然而 * 如果我使用它与一个正常的变量,它的工作正常:
def exampleVar = 'fred'

def string2 = """\
  First line for plain list
  
  $exampleVar

  Last line
""".stripIndent()

产生:

First line for plain list

fred

Last line

这和我预料的一样。
如果要在多行字符串中使用join()数组,是否需要做一些特殊的操作?

uqcuzwp8

uqcuzwp81#

直接来自javadoc:

Strips leading spaces from every line in a CharSequence. 
The line with the least number of leading spaces determines the number to remove.

所以你的连接还应该插入2个或任何数字的空格来匹配最小的ident:

def list = [ 'one', 'two' ]
def listAsString = list.join "\n  "
    
def string = """\
  First line for listAsString

  $listAsString

  Last line
""".stripIndent()

assert string == '''\
First line for listAsString

one
two

Last line
'''

相关问题