I have String like:
test text test
I want to keep single space as it is and replace multiple spaces with
So it will become:
tets text test
Can anyone here please suggest me regex?
You can use following replacement:
String replaced = str.replaceAll("((?<= ) | (?= ))", " ");
Explanation: I am using lookahead and lookbehind features of Regex here. ((?<= ) | (?= )) means find a space which is either preceded by a space (?<= ) OR followed by a space (?= ) This will make sure single space is not replaced but all multiple spaces are replaced. See this link for more details on lookarounds: http://www.regular-expressions.info/lookaround.html
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