In JavaScript, I have the following:
function replaceURLWithHTMLLinks(text) {
var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
return text.replace(exp,"<a href='$1'>$1</a>");
}
It replaces all of the URLs in the input string with a version of the URL that has an anchor tag wrapped around it to turn it into a link. I’m trying to duplicate this functionality in Java with the following function:
private String replaceURLWithHTMLLinks(String text) {
String pattern = "/(\\b(https?|ftp|file):\\/\\/[-A-Z0-9+&@#\\/%?=~_|!:,.;]*[-A-Z0-9+&@#\\/%=~_|])/i";
return text.replaceAll(pattern, "<a href=\"$1\">$1</a>");
}
However, while it works fine in JavaScript it doesn’t find any matches in Java, even for the same input string. Do I need to change something in the pattern, or what’s going on?
You need to get rid of the slashes around the expression and the
iat the end for the Java example. You can specify theiflag separately. So JavaScript’s/blarg/iwould be turned into"(?i)blarg".Your code would become something like: