Removing the url from text using java

前端 未结 7 1828
梦毁少年i
梦毁少年i 2020-12-15 07:59

How to remove the URLs present in text example

String str=\"Fear psychosis after #AssamRiots - http://www.google.com/LdEbWTgD http://www.yahoo.com/mksVZKBz\"         


        
7条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-15 08:37

    m.group(0) should be replaced with an empty string rather than m.group(i) where i is incremented with every call to m.find() as mentioned in one of the answers above.

    private String removeUrl(String commentstr)
    {
        String urlPattern = "((https?|ftp|gopher|telnet|file|Unsure|http):((//)|(\\\\))+[\\w\\d:#@%/;$()~_?\\+-=\\\\\\.&]*)";
        Pattern p = Pattern.compile(urlPattern,Pattern.CASE_INSENSITIVE);
        Matcher m = p.matcher(commentstr);
        StringBuffer sb = new StringBuffer(commentstr.length);
        while (m.find()) {
            m.appendReplacement(sb, "");
        }
        return sb.toString();
    }
    

提交回复
热议问题