java - java中如何将纯文本转换为html超链接?

标签 java

我正在使用当前表达式将纯文本超链接(例如 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/

相关文章:

java - 在到达底部后自动滚动到回收器 View 顶部的最佳方法是什么?

java - 连接两个 AWS EC2 实例以将数据从一个 EC2 实例共享到另一 EC2 实例

java - 向大纪元时间添加天数 [Java]

java - 编写一个返回对象数组中最大对象的方法

java - filterWhen 和 hasElement 的否定

java - 具有不同参数的重载方法的无效方法引用

java - 将对象[][] 转换为字符串? Java Swing

java - 将字符串转换为日期的年份格式不正确

java - Iterable.filter() 可以跳过 "constant"(包括短路)谓词的处理吗?

java - session.update 未在数据库中更新