Groovyでインデントを変更する



インデントするメソッドとインデントを下げる(アンインデント、逆インデント、インデントを消す)
メソッドを作成して綺麗に掃除しましょう。


タブに対応してない簡易版はindentNotab()、unindentNotab()
タブに対応したもので、collect()とjoin()で対応したものが、indent()、unindent()
eachLineで対応したものがindent2()、unindent2()

ソース

test = """\
a
 b
c
    d
        e
\tf
			g
"""




def indentNotab(str,n){
    str.replaceAll(/(?m)^/, " " *n)
}


def indent(str,n, tabStop = 8){
    str.split("\n").toList().collect{line ->
        if (tabStop){
           (" " * n  + line.expand(tabStop)).unexpand(tabStop)
        } else {
           (" " * n ) + line
        }
    }.join("\n")
}

def indent2(str,n, tabStop = 8){
    retStr = ""
    str.eachLine{line ->
        if (tabStop){
          retStr += (" " * n  + line.expand(tabStop)).unexpand(tabStop) + "\n"
        } else {
          retStr += (" " * n ) + line + "\n"
        }
    }
    return retStr
}


def unindentNotab(str, n){
    str.replaceAll(/(?m)^ {0,$n}/, "")
}

def unindent(str, n, tabStop = 8){
    str.split("\n").toList().collect{line ->
        if (tabStop) {
           line.expand(tabStop).replaceAll(/(?m)^ {0,$n}/, "").unexpand(tabStop) 
        } else {
            line.replaceAll(/(?m)^ {0,$n}/, "")
        }
    }.join("\n")
}
def unindent2(str, n, tabStop = 8){
    retStr = ""
    str.eachLine{line ->
        if (tabStop) {
            retStr += line.expand(tabStop).replaceAll(/(?m)^ {0,$n}/, "").unexpand(tabStop) + "\n"
        } else {
            retStr += line.replaceAll(/(?m)^ {0,$n}/, "") + "\n"
        }
    }
    return retStr
}


println test
println indentNotab(test,8)
println indent(test, 8)
println indent2(test, 8)

println unindentNotab(test,8)
println unindent(test,8)
println unindent2(test,8)
println test.stripIndent(8)

実行結果

a
 b
c
    d
        e
	f
			g

        a
         b
        c
            d
                e
        	f
        			g

	a
	 b
	c
	    d
		e
		f
				g
	a
	 b
	c
	    d
		e
		f
				g

a
b
c
d
e
	f
			g

a
b
c
d
e
f
		g
a
b
c
d
e
f
		g





e



コメント

stripIndent(int numChars)は、無条件で指定された文字数分を削ってしまうので、
整形済みのテキストを加工するならば有効だが、インデントがバラバラだったりすると
ハマりそうだ。





実行環境

  • OS:Windows XP
  • Groovy Version: 1.7.8 .expand()、unexpand()が1.7.3以降だから
  • JVM: 1.6.0_12






Groovyの詳細についてはJavadocと以下の書籍を参考にしている。




Dierk Konig、Andrew Glover、Paul King、、Guillaume Laforge、Jon Skeet、杉浦 孝、櫻井 正樹、須江 信洋、関谷 和愛、佐野 徹郎、寺沢 尚史

しばらくすれば2nd Editionが出るはず




問題自体は第2版のもの。rubyと似てる部分も多いので、ヒントにもなる。
写経でもいいが自分で考えるために他言語の例をGroovyで置き換えてる。




青木 峰郎、後藤 裕蔵、高橋 征義、まつもと ゆきひろ

価格: ¥ 2,940
価格は記載時点のものです。購入前にAmazonでご確認ください。




Groovyイン・アクションを読むならあった方が便利かな。

Rubyレシピブックは「ほんたった」で立ててる