適切な文字列リテラルを選ぶ

ソース

hoge="fuga"

println "$hoge"
println "${hoge}"
println "\$hoge=${hoge}"

println '$hoge'
println '${hoge}'
println "'$hoge'=${hoge}"

println "\""
println "\'"

s1 = """1行目の文字列
2行目の文字列
3行目の文字列です。"""



s2 = """\
1行目の文字列
2行目の文字列
3行目の文字列です。
"""

println "--------------------------"
println s1
println "--------------------------"
println s2
println "--------------------------"

実行環境

実行結果

[D:\workspace\groovy_SandBox]groovy StringLiteral.groovy
fuga
fuga
$hoge=fuga
$hoge
${hoge}
'fuga'=fuga
"
'
--------------------------
1行目の文字列
2行目の文字列
3行目の文字列です。
--------------------------
1行目の文字列
2行目の文字列
3行目の文字列です。

--------------------------

メモ

  • ""は変数が展開される ${}でも$でもOK
  • エスケープ文字は\
  • ''は変数が展開されない
  • ヒアドキュメントは"""
  • """\で改行になる
  • 改行して"""で終わると改行が含まれる