Twinkle Soni Twinkle Soni - 3 days ago 5
Java Question

Java: Replace only exactly matching URL

I want to replace only exactly matching link given in String.
My code is as follows:

String originalString = "<a target=\"_blank\" href=\"http://example.com/\"><span style=\"font-size: 12px;\">ABC</span></a>"
+ "<a target=\"_blank\" href=\"http://example.com/contact/\"><span style=\"font-size: 12px;\">Contact</span></a>";

String replacedString = originalString.replace("http://example.com/", "link1");
System.out.println("Replaced String:" + replacedString);


replacedString = "<a target="_blank" href="link1"><span style="font-size: 12px;">ABC</span></a><a target="_blank" href="link1contact/"><span style="font-size: 12px;">Contact</span></a>"

requiredString = "<a target="_blank" href="link1"><span style="font-size: 12px;">ABC</span></a><a target="_blank" href="link2"><span style="font-size: 12px;">Contact</span></a>"


I get Output as replacedString but required Output should be as requiredString.

Thanks in advance.

Answer

Replace the URL with the quotes:

String replacedString = originalString.replace("\"http://example.com/\"", "\"link1\"");
replacedString = replacedString.replace("\"http://example.com/contact/\"", "\"link2\"");
Comments