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

Popular posts from this blog

java - SSE Emitter : Manage timeouts and complete() -

jquery - uncaught exception: DataTables Editor - remote hosting of code not allowed -

java - How to resolve error - package com.squareup.okhttp3 doesn't exist? -