regex - Java replaceAll remove spaces from empty lines -
i'm trying remove spaces lines in block of text contain nothing spaces, leaving line breaks in place.
i tried following:
str = " text\n \n \n text"; str = str .replaceall("\\a +\\n", "\n") .replaceall("(\\n +\\n)", "\n\n") .replaceall("\\n +\\z", "\n");
i expecting output be
" text\n\n\n text"
but instead was
" text\n\n \n text"
the space in third line of block had not been removed. doing wrong here?
use multiline
flag, ^
, $
match beginning , end of each line. problem regex is capturing newline character, next match advance past it, , cannot match.
str.replaceall("(?m)^ +$", "")
Comments
Post a Comment