gpt4 book ai didi

Java:使用replaceAll()替换字符串中的所有URL(URL包含 '\')

转载 作者:太空宇宙 更新时间:2023-11-04 13:30:18 24 4
gpt4 key购买 nike

我正在处理包含大约 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;
}

有什么帮助吗?

最佳答案

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

[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 进行测试

关于Java:使用replaceAll()替换字符串中的所有URL(URL包含 '\'),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32266211/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com