简体   繁体   中英

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

"""

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

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.

Groovy golf!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM