可以使用正则表达式来去除空行。

示例代码:

def str = """
This is a
test

of

a multiline
string
"""
def result = str.replaceAll("(?m)^[ \t]*\r?\n", "")
println result

输出结果:

This is a
test
of
a multiline
string

解释:

  • (?m) 表示多行模式,即 ^$ 匹配每行的开头和结尾。
  • ^[ \t]*\r?\n 匹配空行,其中 ^[ \t]* 表示匹配行头的空格和制表符,\r?\n 表示匹配换行符。
groovy string 字符串 去除空行

原文地址: http://www.cveoy.top/t/topic/dfp6 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录