Remove empty line from a multi-line string with Java

旧时模样 提交于 2021-02-19 01:28:45

问题


I have a multi-line string and some empty lines between other lines. It looks like:

def msg = """
                AAAAAA

                BBBBBB


                CCCCCC

                DDDDDD







                EEEEEE
                TEST
                FFFFF


                GGGGGG
"""

I tried some regex expression with :

msg = msg.replaceAll('(\n\\\\s+\n)+', '')

Or

msg = msg.replaceAll('(\r?\n){2,}', '$1');

But nothing is good about what I'm looking...

Is it possible to remove only empty lines? to get something like that :

def msg = """
                    AAAAAA
                    BBBBBB
                    CCCCCC
                    DDDDDD
                    EEEEEE
                    TEST
                    FFFFF
                    GGGGGG

"""

回答1:


Use regex (?m)^[ \t]*\r?\n" to remove empty lines:

log.info msg.replaceAll("(?m)^[ \t]*\r?\n", "");

To remain only 1 line use [\\\r\\\n]+:

log.info text.replaceAll("[\\\r\\\n]+", "");

If you want to use the value later, then assign it

text = text.replaceAll("[\\\r\\\n]+", "");



回答2:


Your current attempt seems very much on the right track, and I think the logic you want is to replace two or more newlines with just a single newline:

output = msg.replaceAll("(\r?\n)(?:\r?\n){1,}", "$1");

The trick here, to capture the actual newline type being used (\n for Linux or \r\n for Windows), is to capture a single \r?\n first, followed then by at least one more newline.




回答3:


Groovy golf!

msg.split('\n')
   .findAll { it.trim() }
   .join('\n')


来源:https://stackoverflow.com/questions/57146506/remove-empty-line-from-a-multi-line-string-with-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!