在 Groovy 多行字符串中去除缩进 [英] Strip indent in Groovy multiline strings

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

问题描述

不幸的是,多行字符串上的 stripIndent 不起作用.旁注:我的 IDE 代码样式首选项只允许空格缩进(制表符将被空格替换).不过我觉得这个应该没有关系.

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()

不打印

This
is
multiline

正如预期的那样.

输出带有缩进.

This 
               is
               multiline

这里出了什么问题?

我使用 Groovy 2.0.7 和 Eclipse Indigo SR2.

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.

推荐答案

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

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.

给定您的字符串,这将是 This 前面的一个空格,它将从多行字符串的每一行中删除.

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天全站免登陆