Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove empty line from a multi-line string with Java

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

"""
like image 294
msommer Avatar asked Jul 22 '19 12:07

msommer


1 Answers

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]+", "");
like image 125
user7294900 Avatar answered Oct 20 '22 01:10

user7294900