gpt4 book ai didi

Java URL 正则表达式不匹配

转载 作者:行者123 更新时间:2023-12-01 17:25:11 29 4
gpt4 key购买 nike

我正在尝试计算 Java 字符串中 URL 的数量:

String test = "This http://example.com is a sentence https://secure.whatever.org that contains 2 URLs.";
String urlRegex = "<\\b(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]>";
int numUrls = 0;
pattern = Pattern.compile(urlRegex);
matcher = pattern.matcher(test);
while(matcher.find())
numUrls++;
System.err.println("numUrls = " + numUrls);

当我运行它时,它告诉我字符串中有零个(不是 2 个)URL。有什么想法吗?提前致谢!

最佳答案

<> urlRegex 中的字符导致您的模式和输入之间不匹配 test String 。删除它们将产生 numUrls 2 的值正如预期的那样。

关于Java URL 正则表达式不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15508081/

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