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 """ 回答1: Use regex (?m)^[ \t]*\r