Koerr
Koerr

Reputation: 15723

how can I trim <br> tags using regex in java?

String s="<br /><br /><br /><br /><br />hello world!<br /><br /><br />";
s=s.replaceAll("<br /><br />", "<br />");
System.out.println(s);
//result: <br /><br /><br />hello world!<br /><br />

I want to get <br />hello world!<br />

how to do? thanks :)

Upvotes: 2

Views: 1416

Answers (4)

TheExplorerLost
TheExplorerLost

Reputation: 155

Try this:

String healthyString = badString.replaceAll("(<br(.*?\\/?)>)+", "<br />");

or, according to your example...

s = s.replaceAll("(<br(.*?\\/?)>)+", "<br />");

This expression will solve the problem. It matches all line-break combinations: <br>, <br/>, and <br />.

Upvotes: 0

tvkanters
tvkanters

Reputation: 3523

Use s = s.replaceAll(/(<br\s*\/?>)+/, "<br />");. This should replace any number of <br />s by one.

Upvotes: 5

user unknown
user unknown

Reputation: 36229

s = s.replaceAll ("(<br />)+", "<br />")

Upvotes: 3

zzzzBov
zzzzBov

Reputation: 179046

/(<br \/>)+<br \/>/ -> "<br />"

Upvotes: 0

Related Questions