124697
124697

Reputation: 21891

How can I remove a word from a string if it occures more than 1 in a row with regex

I want to remove the word "<br>" if it occures more than once consecutively. example

"word word <br><br>" becomes "word word <br>"

and "word <br><br><br> word <br><br>" becomes "word <br> word<br>"

I want to use replace or replace all if thats possible to keep it short

Upvotes: 3

Views: 2861

Answers (3)

lukastymo
lukastymo

Reputation: 26819

This code is good to simplest situation:

str.replaceAll("(<br>)+", "<br>");

But if you want replace all br (case insensitive + ignore whitespaces), e.g.:

my word <BR>  <BR> blah blah -> my word <br> blah blah

I recommend you:

str.replaceAll("(?i)(<br>(\\s)*)+", "<br>")

Upvotes: 1

Jeremy Whitlock
Jeremy Whitlock

Reputation: 3818

You can write a regex that matches the pattern only if it occurs more than one time.

Upvotes: 0

aioobe
aioobe

Reputation: 421170

I want to use replace or replace all if thats possible to keep it short

Sure, it's possible:

yourString = yourString.replaceAll("(<br>)+", "<br>");

It basically means replace all "<br> one or more times" with just "<br>".

Upvotes: 6

Related Questions