Java 如何在html文档中用超链接替换普通url
我正在尝试替换html文档中指向超链接的普通链接。 我的逻辑是Java 如何在html文档中用超链接替换普通url,java,html,regex,hyperlink,regex-negation,Java,Html,Regex,Hyperlink,Regex Negation,我正在尝试替换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
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);
}
而且它根本不应该影响2 我建议您在这里使用 示例代码
String text=“更改此项:http://yahoo.com "foo.com",;
文档d=Jsoup.parse(文本);
字符串newHtmlCode=“”;
字符串oldHtmlCode=d.outerHtml();
列出textNodes=d.body().textNodes();
Matcher m=Patterns.WEB\u URL.Matcher(“”);
用于(TextNode TextNode:textNodes){
m、 重置(textNode.text());
字符串片段=”;
while(m.find()){
fragment=m.replaceAll(“”);
textNode.replaceWith(新元素(Tag.valueOf(“span”),“”).html(片段));
}
newHtmlCode=d.outerHtml().replaceAll(“\”\\Q***\\E(?!https?:/)”、“\”http:/”).replaceAll(“\”\\Q***\\E(https?:/)”、“\”$1”);
}
System.out.println(“之前:\n\n”+oldHtmlCode);
System.out.println(“-------------------------------”;
System.out.println(“之后:\n\n”+newHtmlCode);
输出
之前:
更改此项:http://yahoo.com foo.com
----------------------------
之后:
更改此项:
是否可以不使用解析器执行此操作。我在找正则表达式。@Subham检查我的答案我使用正则表达式查找普通链接。Jsoup相当快。@Subham检查我的新答案。
<p class="MsoNormal"><a href="awbs://www.google.com" target="_BLANK">https://www.google.com</a> normal address https</p>
<p class="MsoNormal"><a href = "https://www.yahoo.com>https://www.yahoo.com</a></p>
BEFORE:
<html>
<head></head>
<body>
<a href="http://google.com">Don't change this link</a> Change this: http://yahoo.com foo.com
</body>
</html>
----------------------------
AFTER:
<html>
<head></head>
<body>
<a href="http://google.com">Don't change this link</a>
<span> Change this: <a href="http://yahoo.com">http://yahoo.com</a> <a href="http://foo.com">foo.com</a></span>
</body>
</html>