【问题标题】:Java: Replacing all URLs from String (URL contains '\') using replaceAll()Java:使用replaceAll()替换字符串中的所有URL(URL包含'\')
【发布时间】:2015-11-22 19:54:44
【问题描述】:

我正在处理一个包含大约 1000 万个文件的语料库。有些文件的 url 中包含反斜杠 ('\')。我想替换这些文件中的所有 URL。以下工作正常,直到找到包含反斜杠的 URL。

public static String removeUrl(String str)
{
    String urlPattern = "((https?|ftp|gopher|telnet|file|Unsure):((//)|(\\\\))[\\w\\d:#@%/;$~_?\\+-=\\\\\\.&]*)";
    Pattern p = Pattern.compile(urlPattern, Pattern.CASE_INSENSITIVE);
    Matcher m = p.matcher(str);
    while (str!=null && m.find()) {
        str = str.replaceAll(m.group(0)," ").trim(); // ERROR is occuring here when m.group(0) has URL with '\'
    }
    return str;
}

有什么帮助吗?

【问题讨论】:

  • 你能补充一些例子吗?
  • 请在示例中告诉您所需的输出

标签: java regex replaceall


【解决方案1】:

这与转义反斜杠有关: removeUrl("http://go.com\\\\") 不会抛出错误,但 removeUrl("http://go.com\\") 会。您可能必须在替换所有之前操作字符串,例如str.replaceAll("\\\\", "");

此外,仅当您str.replaceAll("\\", ""); 而不是str.replace("\\", ""); 时才会引发异常

编辑:刚刚看到this

【讨论】:

    【解决方案2】:

    这个正则表达式对我有用。

    [a-zA-Z]+:\/\/([a-zA-Z0-9\.\-_])+(:[0-9]+)?([\/\\][a-zA-Z0-9\._\-]*)*(\?(&?[a-zA-Z0-9_\-\.]+=[a-zA-Z0-9_\-\.]+)+)?
    

    它匹配所有这些

    http://test.test.test:123/test.test/test?blah=23&bluh=23
    http://test.test.test/test.test/?blah=blah
    http://ttes-test.comsa234/ase/ase
    abc://test.test
    abc://test.test:900
    abc://test.test/
    abc://test.test\
    abc://test.test\test
    abc://test.test:90/test\test/test
    abc://wow/test?this=works&and=worksagain
    cde://yay/what/yes.com/hi_there\?param=value&param=value
    withdash://its-dash/another-dash\okay
    

    您可以使用 regex101 进行测试

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-07
      • 2012-06-10
      相关资源
      最近更新 更多