【问题标题】:How can I textwrap.dedent() for Groovy如何为 Groovy 设置 textwrap.dedent()
【发布时间】:2015-08-22 09:56:50
【问题描述】:

Python 和 Groovy 都有一个简洁的功能,可以让您编写多行字符串:

def foo = '''\
    [owner]
    name=bar

    [database]
    server=127.0.0.1'''

等同于:

def foo = '        [owner]\n        name=bar\n\n        [database]\n        server=127.0.0.1'

在 Python 中,textwrap.dedent() 函数从文本的每一行中删除任何常见的前导空格。

有没有类似 Python textwrap.dedent() for Groovy 的东西可以给我:

    def foo = '[owner]\nname=bar\n\n[database]\nserver=127.0.0.1'

【问题讨论】:

  • 我最终自己移植了一些实现,但如果有人知道更好的方法,请回答

标签: groovy


【解决方案1】:

试试stripIndent

即:

foo.stripIndent()

【讨论】:

    【解决方案2】:

    我最终基于this GO implementation 编写了自己的实现。

    /**
     * Dedent removes any common leading whitespace from every line in text.
     *
     * This can be used to make multiline strings to line up with the left edge of
     * the display, while still presenting them in the source code in indented
     * form.
     */
    def dedent(text) {
        def whitespace_only = ~/(?m)^[ \t]+$/
        def leading_whitespace = ~/(?m)(^[ \t]*)(?:[^ \t\n])/
    
        text = text.replaceAll(whitespace_only, '')
        def indents = text.findAll(leading_whitespace) { match, $1 -> $1 }
    
        // Look for the longest leading string of spaces and tabs common to
        // all lines.
        def margin = null
        for (i = 0; i < indents.size(); i++) {
            if (i == 0) {
                margin = indents[1]
            } else if (indents[1].startsWith(margin)) {
                // Current line more deeply indented than previous winner:
                // no change (previous winner is still on top).
                continue
            } else if (margin.startsWith(indents[1])) {
                // Current line consistent with and no deeper than previous winner:
                // it's the new winner.
                margin = indents[1]
            } else {
                // Current line and previous winner have no common whitespace:
                // there is no margin.
                margin = ""
                break
            }
        }
    
        if (margin != "") {
            text = text.replaceAll(~"(?m)^${margin}", '')
        }
        return text
    }
    

    但我是 Groovy 的新手,虽然代码在我的第一次测试中看起来是正确的,但它可能写得不好。

    【讨论】:

      猜你喜欢
      • 2010-09-05
      • 1970-01-01
      • 2021-11-16
      • 1970-01-01
      • 2016-06-08
      • 2013-07-24
      • 1970-01-01
      • 1970-01-01
      • 2015-11-10
      相关资源
      最近更新 更多