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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With