String replace continuous whitespace only

java, regex

Solution

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

Problem

I have String like: ``` test text test ``` I want to keep single space as it is and replace multiple spaces with `&nbsp;` So it will become: ``` tets&nbsp;&nbsp;&nbsp;&nbsp;text test ``` Can anyone here please suggest me `regex`?

Original source

Related problems