【发布时间】:2014-02-21 06:11:24
【问题描述】:
我正在尝试将普通链接替换为 html 文档中的超链接。 我的逻辑是
private static final Pattern WEB_URL_PROTOCOL = Pattern.compile("(?i)http|https://");
StringBuffer sb = new StringBuffer();
if (text != null) {
// Escape any inadvertent HTML in the text message
text = EmailHtmlUtil.escapeCharacterToDisplay(text);
// Find any embedded URL's and linkify
Matcher m = Patterns.WEB_URL.matcher(text);
while (m.find()) {
int start = m.start();
if (start == 0 || text.charAt(start - 1) != '@') {
String url = m.group();
Matcher proto = WEB_URL_PROTOCOL.matcher(url);
String link;
if (proto.find()) {
lower case protocol link.
link = proto.group().toLowerCase() + url.substring(proto.end());
} else {
link = "http://" + url;
}
String href = String.format("<a href=\"%s\">%s</a>", link, url);
m.appendReplacement(sb, href);
}
else {
m.appendReplacement(sb, "$0");
}
}
m.appendTail(sb);
}
此代码已成功找出 html 文档中的所有链接。但问题是它也找到了超链接。所以我想排除超链接并只想找到普通链接 例如它应该排除
<p class="MsoNormal"><a href="awbs://www.google.com" target="_BLANK">https://www.google.com</a> normal address https</p>
但普通链接https://www.google.com 应替换为超链接
编辑 如果文档包含这样的文本 - 1.https://www.yahoo.com
2.https://www.google.com普通地址https所以在这里我想用
替换https://www.yahoo.com
<p class="MsoNormal"><a href = "https://www.yahoo.com>https://www.yahoo.com</a></p>
而且它根本不应该影响 2 。
【问题讨论】:
标签: java html regex hyperlink regex-negation