在groovy多行字符串中缩进缩进 [英] strip indent in groovy multiline strings

查看:448
本文介绍了在groovy多行字符串中缩进缩进的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不幸的是,多行字符串上的stripIndent不起作用。
附注:我的IDE代码样式首选项只允许空格缩进(制表符将被空格替换)。但我认为这应该没有问题。

  def s =这

多行

println s.stripIndent()

不打印

 

多行

如预期的那样。



输出结果为缩进。

 

多行

这里出了什么问题?



我使用Groovy 2.0.7和Eclipse Indigo SR2。

似乎在第一行中使用反斜杠(字符串连续字符)消失。但是我不明白为什么这是必须的。

解决方案

您可以使用 .stripIndent() 删除多行字符串的缩进。但是您必须记住,如果没有给出缩进量,它将自动从包含至少个前导空格的行确定。



考虑到你的字符串,这将是这个之前的一个空格,它将从多行字符串的每一行中删除。

  def s =这

多行

要解决此问题,您可以转义多行字符串的第一行,如下例所示,以获得您的期望结果:

  def s =\ 


多行


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.

解决方案

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

这篇关于在groovy多行字符串中缩进缩进的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆