Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trimming trailing whitespace from every line in a multi-line string using replaceAll

Tags:

java

regex

Please explain why in this expression, the replacement only occurs once, at the end of the string.

"1  \n3  \n5  ".replaceAll(" +$", "x") // => "1  \n3  \n5x"

According to the Java 7 docs for Pattern, $ is supposed to match the end of a line, and \z match the end of input (the string).

My goal is to replace trailing whitespace at the end of every line in a string. The "x" replacement is merely a way to better visualize what is being replaced.

I would think a regular expression and String.replaceAll ought to be able to do this. If replaceAll is not able to perform this operation, please suggest a concise alternative.

like image 435
Edward Anderson Avatar asked Dec 09 '22 06:12

Edward Anderson


1 Answers

To replace the trailing whitespace of each line, you need to use the (?m) (multi-line) modifier.

"1  \n3  \n5  ".replaceAll("(?m) +$", "x") //=> "1x\n3x\n5x"

Note: This modifier makes the ^ and $ match at the start and end of each line.

like image 175
hwnd Avatar answered Dec 11 '22 10:12

hwnd