使用java从文本中删除url

NLP*_*AVA 13 java regex

如何删除文本示例中的URL

String str="Fear psychosis after #AssamRiots - http://www.google.com/LdEbWTgD http://www.yahoo.com/mksVZKBz";
Run Code Online (Sandbox Code Playgroud)

使用正则表达式?

我想删除文本中的所有网址.但它没有用,我的代码是:

String pattern = "(http(.*?)\\s)";
Pattern pt = Pattern.compile(pattern);
Matcher namemacher = pt.matcher(input);
if (namemacher.find()) {
  str=input.replace(namemacher.group(0), "");
}
Run Code Online (Sandbox Code Playgroud)

NLP*_*AVA 19

输入String包含网址的内容

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);
        int i = 0;
        while (m.find()) {
            commentstr = commentstr.replaceAll(m.group(i),"").trim();
            i++;
        }
        return commentstr;
    }
Run Code Online (Sandbox Code Playgroud)

  • 3 到 4 个小时后,我意识到您的代码不起作用 (2认同)

svz*_*svz 5

好的,您尚未提供有关文本的任何信息,因此假设您的文本看起来像这样:"Some text here http://www.example.com some text there",您可以这样做:

String yourText = "blah-blah";
String cleartext = yourText.replaceAll("http.*?\\s", " ");
Run Code Online (Sandbox Code Playgroud)

这将删除所有从“ http”开始直到第一个空格字符的序列。

您应该阅读有关String类的Javadoc 。它将为您弄清楚。

  • 它必须是`yourText.replaceAll(“ http。*?\\ s”,“”);` (2认同)