我正在使用当前表达式将纯文本超链接(例如 http 或 https)转换为 html 超链接
String pattern = "(?:https|http)://([^\\s\\|]+)";
但是,在将通过此正则表达式模式的消息内容中,我有类似 [video]http://www.yahoo.com[video] 的内容。
对于两个视频括号之间的此类内容。我不希望它被转换为html超链接,因为它会显示在页面上。
如何解决这个问题?
最佳答案
使用负前瞻和后瞻使用 (?<!...)
和(?!...)
:
String link = "(?:https|http)://([^\\s\\|]+)";
String pattern = "(?<!\\[video\\])" + link + "(?!\\[video\\])";
Pattern p = Pattern.compile(pattern);
System.out.println(p.matcher("[video]http://www.yahoo.com[video]").matches());
System.out.println(p.matcher("http://www.yahoo.com").matches());
输出:
false
true
完整示例:
public static void main(String... args) {
Pattern pattern = Pattern.compile(
"(?<!\\[video\\])(?:https|http)://([^\\s\\|]+)(?!\\[video\\])");
String text = "This is some example text with a link" +
"[video]http://videolink[video] that should not be replaced" +
"and another link that should be" +
"replaced http://www.example.com";
Matcher m = pattern.matcher(text);
StringBuffer sb = new StringBuffer();
while (m.find())
m.appendReplacement(sb, "<a href=\""+m.group()+"\">"+m.group() +"</a>");
m.appendTail(sb);
System.out.println(sb);
}
输出:
This is some example text with a link [video]http://videolink[video] that should not be replaced and another link that should be replaced http://www.example.com
关于java - java中如何将纯文本转换为html超链接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10876925/