是否有运算符可以修剪多行字符串中的缩进?

Bin*_*hel 9 groovy multilinestring

这在Groovy中真的很不错:

println '''First line,
           second line,
           last line'''
Run Code Online (Sandbox Code Playgroud)

多行字符串.我已经在一些语言中看到了更进一步的工具,可以删除第2行的缩进,因此该语句将打印:

First line,
second line,
last line
Run Code Online (Sandbox Code Playgroud)

并不是

First line,
           second line,
           last line
Run Code Online (Sandbox Code Playgroud)

在Groovy中有可能吗?

kda*_*bir 14

你可以使用stripMargin()这个:

println """hello world!
        |from groovy 
        |multiline string
    """.stripMargin()
Run Code Online (Sandbox Code Playgroud)

如果你不想要前导字符(在这种情况下就像管道一样),那么也有stripIndent(),但是字符串需要格式化不同(因为最小缩进很重要)

println """
        hello world!
        from groovy 
        multiline string
    """.stripIndent()
Run Code Online (Sandbox Code Playgroud)

来自的文档 stripIndent

从String中的每一行中删除前导空格.前导空格数最少的行确定要删除的数量.在计算要去除的前导空格的数量时,将忽略仅包含空格的行.


更新:

关于使用操作员这样做,我个人不建议这样做.但是对于记录,可以通过使用扩展机制或使用类别(更简单和更笨重)来完成.分类示例如下:

class StringCategory {
    static String previous(String string) { // overloads `--`
        return string.stripIndent()
     }
}

use (StringCategory) {
    println(--'''
               hello world!
               from groovy 
               multiline string
           ''') 
}
Run Code Online (Sandbox Code Playgroud)