Java在字符串中查找URL并创建HTML链接标记

时间:2014-12-02 09:14:35

标签: java html

在我的字符串中我只有这个结果:

content = "Hello world, visit this link: www.stackoverflow.com";

content = "Hello world, visit this link: http://www.stackoverflow.com";

content = "Hello world, visit this link: http://stackoverflow.com";

现在我想在这个字符串中找到url并最终创建html链接标记,就像这个结果一样:

HtmlContent = "Hello world, visit this link: <a href="http://stackoverflow.com">http://stackoverflow.com </a> ";

如何获得此结果?

HtmlContent = "Hello world, visit this link: <a href="[http://|www.] stackoverflow.com">[http://|www.]stackoverflow.com </a> ";

3 个答案:

答案 0 :(得分:2)

我会将句子拆分成一个数组,并检查每个数组中是否包含wwwhttp

string[] possibleLinks = content.split(" ");
for (int i = 0; i < possibleLinks.length; i++)
    if (possibleLinks[i].contains("http://") || possibleLinks[i].contains("www."))
    {
        //Use the link here, which will be posibleLinks[i]
    }

由于您实际上想要修改现有字符串,您可以尝试这样做:

String content = "Hello World! Visit: http://www.lol.com";
int a = 0, b = 0;

a = content.contains("http://") ? content.indexOf("http://") : content.indexOf("www.");
b = content.indexOf(".com") + 4;

if (a != -1)
{
    String link = content.substring(a,b);
    content = content.substring(0,a) + "<a href=\"" + link + "\"/>" + link + "</a>";
}

System.out.println(content);

它不是世界上最漂亮的代码,但我已经对它进行了测试,并且它有效。

答案 1 :(得分:2)

您可以尝试这样:

String content = "Hello world, visit this link: www.stackoverflow.com";

    String[] splitted = content.split(" ");
    for (int i = 0; i < splitted.length; i++) {
        if ((splitted[i]).contains("www.")) { // use more statements for
                                                // http:// etc..
            System.out.println(splitted[i]); //just checking the output
            String link = "<a href=\"" + splitted[i] + "\">" + splitted[i] + "</a>";

            System.out.println(link); //just checking the output
        }
    }

使用\&#34;在字符串中写入字符串中的引号。

答案 2 :(得分:2)

将您的content字符串拆分为:

String[] tokens = content.split(" ");

循环遍历tokens并使用正则表达式标识令牌有效 url

for (int i = 0; i < tokens.length; i++){
    String regex = "^(https?:\/\/)?(www.)?([a-zA-Z0-9]+).[a-zA-Z0-9]*.[a-z]{3}.?([a-z]+)?$";

    // if valid match replace this token with desired string. as in your case:
    if(Pattern.matches(regex, tokens[i])){
        tokens[i] = "<a href='"+tokens[i]+"'>"+tokens[i]+"</a>";
    }
}

然后加入令牌

StringBuilder sbStr = new StringBuilder();
for (int i = 0, i = tokens.length; i++) {
    if (i > 0)
        sbStr.append(" ");
    sbStr.append(aArr[i]);
}

System.out.println(sbStr.toString()); // your expected result.