Andrea
Andrea

Reputation: 6125

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

I am trying to perform a cleaning of a HTML text, and I want to replace multiple occurrencies of   with a single occurrence of it.

So, for example:

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

should become

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

despite the number of &nbsp;s, that could vary.

I could use a replace() in a loop, repeating until the result varies. But I think there could exist a one-linear or at least a smarter method.

Upvotes: 0

Views: 141

Answers (1)

user6073886
user6073886

Reputation:

String has a second method to replace substrings besides the standard replace that takes a regular expression as an argument called replaceAll. (*)

With that method you can easily do it with a simply

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

(*) That those 2 method are really badly named and often confuse beginners is a very well known weakness of java/the String class.

Upvotes: 1

Related Questions