将多次出现的子字符串替换为单次出现的子字符串

Replace multiple occurrencies of a substring with a single occurrence of it

我正在尝试清理 HTML 文本,我想用一次出现的   替换多次出现的  

因此,例如:

<o:p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</o:p></b></p> 

应该变成

<o:p>&nbsp;</o:p></b></p>

尽管 &nbsp; 的数量可能会有所不同。

我可以在循环中使用 replace(),重复直到结果不同。但我认为可能存在一种单线性或至少一种更智能的方法。

除了标准 replace 之外,字符串还有另一种替换子字符串的方法,该方法将正则表达式作为参数 replaceAll。 (*)

使用该方法,您可以轻松地通过

 .replaceAll("(&nbsp;)+", "&nbsp;")

(*) 这 2 个方法的命名真的很糟糕,经常让初学者感到困惑,这是 java/the String class.

的一个众所周知的弱点