`

如何将一个http link转化成href(java)

阅读更多

public static String extractHyperlink(String desc) {
if (desc == null) {
return null;
}
// if there are bullet points we enforce a lower limit and just allow one line of <li/>
int pos = desc.indexOf("http://");
if (pos == -1 || (pos > 0 && (desc.charAt(pos - 1) == '"' || desc.charAt(pos - 1) == '>'))) {
// we can't count the already extracted link
return desc;
} else {
String next = desc.substring(pos);
int end1 = next.indexOf(" ");
int end2 = next.indexOf("\n");
int end = next.length();
if (end1 != -1)
end = Math.min(end, end1);
if (end2 != -1)
end = Math.min(end, end2);
// this is a situation where the link is ended with a punctuation
// so we have to remove all non-letters at the end
while (true) {
char c = next.charAt(end - 1);
// '/' to '9', then 'A' to 'Z', then 'a' to 'z'
if (c > 'z' || c < '/' || (c > 'Z' && c < 'a') || (c > '9' && c < 'A')) {
end--;
} else {
break;
}
}
if (end == next.length()) {
String url = next.substring(0);
desc = desc.substring(0, pos) + "<a href=\"" + url + "\" target=\"_blank\">" + url + "</a>";
} else {
String url = next.substring(0, end);
desc = desc.substring(0, pos) + "<a href=\"" + url + "\" target=\"_blank\">" + url + "</a>" + extractHyperlink(next.substring(end));
}
return desc;
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics