Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String replace continuous whitespace only

Tags:

java

regex

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?

like image 359
rot Avatar asked Aug 27 '26 07:08

rot


1 Answers

You can use following replacement:

String replaced = str.replaceAll("((?<= ) | (?= ))", "&nbsp;");

Live Demo: http://ideone.com/kNb7rd

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

like image 63
anubhava Avatar answered Aug 28 '26 19:08

anubhava



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!