我想检查文本是否有多个链接 因此,我从以下代码开始:
private static void twoOrMorelinks(String commentstr){
String urlPattern = "^.*((?:http|https):\\/\\/\\S+){1,}.*((?:http|https):\\/\\/\\S+){1,}.*$";
Pattern p = Pattern.compile(urlPattern,Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(commentstr);
if (m.find()) {
System.out.println("yes");
}
}
但是上面的代码不是很专业,我正在寻找如下内容:
private static void twoOrMorelinks(String commentstr){
String urlPattern = "^.*((?:http|https):\\/\\/\\S+){2,}.*$";
Pattern p = Pattern.compile(urlPattern,Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(commentstr);
if (m.find()) {
System.out.println("yes");
}
}
但是此代码不起作用,例如我希望代码显示与以下文本的匹配,但事实并非如此:
They say 2's company watch live on...? http://www.le testin this code http://www.lexilogos.com
有什么想法吗?
最佳答案
只需使用它来计算您拥有的链接数量:
private static int countLinks(String str) {
int total = 0;
Pattern p = Pattern.compile("(?:http|https):\\/\\/");
Matcher m = p.matcher(str);
while (m.find()) {
total++;
}
return total;
}
然后
boolean hasMoreThanTwo = countLinks("They say 2's company watch live on...? http://www.le testin this code http://www.lexilogos.com") >= 2;
如果您只想知道是否有两个或更多,请在找到两个后退出。
关于java - 检查文本是否有多个链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32531389/