I need a Java code to take this text ” text1 [example1]http://example1.com [example2]http://example2.com text2 ….” and return it as the following:
text1 <a target='_blank' href='http://example1.com'>example1</a> <a target='_blank' href='http://example2.com'>example2</a> text2
i mean whenever it finds this pattern [example2]http://example2.com in a text to take and put it in html hyperlink. Please help.. that what i have done till now but its not working
ViolationTableItem item = new ViolationTableItem(m_violation);
String dataSource = "";
String copyDataSource="";
try {
dataSource = item.getUi().getViolation().getBlackListEntries()
.getDataSources();
Matcher matcher = Pattern.compile(
"(\\[.*?\\])(.*://[^<>[:space:]]+[[:alnum:]/])").matcher(
dataSource);
while (matcher.find()) {
String matchedLink = matcher.group();
Matcher nameMatcher = Pattern.compile("\\[.*?\\]").matcher(
matchedLink);
String nameMatched = "";
String nameMatched2 = "";
String linkableText = "";
String[] tst = matchedLink.split("\\[.*?\\]");
for (int i = 1; i < tst.length; i++) {
if (nameMatcher.find()) {
nameMatched = nameMatcher.group();
// System.out.println(nameMatched);
nameMatched2 = matchedLink.replace(nameMatched, "");
// System.out.println(nameMatched2);
}
if (tst[i] != null && !tst[i].equals("")) {
linkableText = "<a target='_blank' href='"
+ tst[i]
+ "'>"
+ nameMatched.replaceAll("\\[", "").replaceAll(
"\\]", "") + "</a>";
copyDataSource += dataSource.replace(matchedLink,
linkableText) + " ";
}
}
}
} catch (Exception ne){
return copyDataSource;
}
return copyDataSource;
Thanks in advance!
You can do this easily with
String.replaceAll():prints
The regex looks for a pair of brackets, captures everything inside and after up until the next space, and replaces it with the link string.
$1and$2are used to find what was captured in the first and second parantheses.If you dont want it to match any brackets, but for example just those followed by
http://, just change the second(.*?)to(http://.*?).