如何从字符串中删除此URL?

时间:2013-11-22 10:48:24

标签: java regex

我有以下字符串:

String description= errex for Screen Share 
https://ednovo.webex.com/ednovo/j.php?ED=224466857&UID=1465621292&RT=MiM0
You can find the meeting notes here https://docs.yahoo.com/a/filter.org/document/d/1Luf_6Q73_Lm30t3x6wHS_4Ztkn7HfXDg4sZZWz-CuVw/edit?usp=sharing

我想删除网址链接并以此结尾:

String description=errex for Screen Share You can find the meeting notes here 

我尝试了以下代码,但没有检测到网址:

private String removeUrl(String commentstr)
    {
        String commentstr1=commentstr;
        String urlPattern = "((https?|ftp|gopher|telnet|file|Unsure|http):((//)|(\\\\))+[\\w\\d:#@%/;$()~_?\\+-=\\\\\\.&]*)";
        Pattern p = Pattern.compile(urlPattern,Pattern.CASE_INSENSITIVE);
        Matcher m = p.matcher(commentstr1);
        int i=0;
        while (m.find()) {
            commentstr1=commentstr1.replaceAll(m.group(i),"").trim();
            i++;
        }
        System.out.println("After url filter" +commentstr1);

        return commentstr1;
    }

这里有什么问题?

2 个答案:

答案 0 :(得分:7)

这将删除网址:

description = description.replaceAll("https?://\\S+\\s?", "");

从最后的小\\s?开始,确保在从两个空格中删除URL后不会获得双倍空格。

答案 1 :(得分:3)

String description= "errex for Screen Share https://ednovo.webex.com/ednovo/j.php?ED=224466857&UID=1465621292&RT=MiM0 " +
    "You can find the meeting notes here https://docs.yahoo.com/a/filter.org/document/d/1Luf_6Q73_Lm30t3x6wHS_4Ztkn7HfXDg4sZZWz-CuVw/edit?usp=sharing";

System.out.println(description.replaceAll("\\S+://\\S+", ""));