Dan D.
Dan D.

Reputation: 32391

String regex with groups

I try to use the String.replaceAll method for replacing a String like <br> with <br/>. Because <br> can be something more complicated like <br style="">, I need the same regex to work on both cases.

I tried something like:

String s = "<something><br><br style=\"\"></something>";
s = s.replaceAll("<br(.*)>", "<br$1/>");

but it doesn't seem like I am very successful.

Upvotes: 0

Views: 51

Answers (2)

Rakesh KR
Rakesh KR

Reputation: 6527

Try using this expression:

s = s.replaceAll("<br(.*?)>", "<br$1/>");

Upvotes: 0

Toto
Toto

Reputation: 91415

Make the regex ungreedy:

s = s.replaceAll("<br(.*?)>", "<br$1/>");

or:

s = s.replaceAll("<br([^>]*)>", "<br$1/>");

Upvotes: 1

Related Questions