Remove empty line from a multi-line string with Java

msommer :

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

"""
user7294900 :

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]+", "");

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=125050&siteId=1