user1670443
user1670443

Reputation: 471

How to remove the first occurance of a sub string in a string in java?

I have a HTML content in the form of String. There are many hyper links in the string. How can I remove only first link in the string? Please guide me.

String html = "abcdef<a href=some dynamic url>link1</a>ghijkl<a href=some url>link2</a>mnopq<a href=some url>link3</a>";

I want to remove the "link1" along with reference url from above string.

Upvotes: 0

Views: 140

Answers (4)

R. Oosterholt
R. Oosterholt

Reputation: 8080

You can use a regular expression. Example:

html.replaceFirst("<a[^>]+>[^>]+</a>", "");

Upvotes: 1

Dhana Krishnasamy
Dhana Krishnasamy

Reputation: 2176

I would do something like

String matchATag="<a[^>]*>([^<]+)</a>";
html=html.replaceFirst(matchATag,"");

Upvotes: 2

mkuff
mkuff

Reputation: 1682

For html processing i would suggest jsoup (http://jsoup.org/). You can also specify the replacement behaviour in this lib.

Upvotes: 0

Bozho
Bozho

Reputation: 597096

You might try to match the link element with regex, but that's a recipe for problems.

You'd better get an HTML parser like NekoHTML, find the first link, and remove it.

Upvotes: 0

Related Questions