java - 检查文本是否有多个链接

标签 java regex

我想检查文本是否有多个链接 因此,我从以下代码开始:

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/

相关文章:

java - 正则表达式验证仅适用于一个字符

javascript - BBCode 标签 javascript 的正则表达式

regex - 不要在 htaccess 中重定向子域

Java:JButton 和 ArrayList:从 ArrayList 添加到 JPanel

java - 通过比较两个参数打印连续的数字

java - 使用 JDB 和 Gradle 调试 Java

regex - 如何删除 vb.net 中方括号之间的空格?

java - 如何使用 LatLng 获取起始位置/位置。我确实有一个正在移动的当前位置/位置

java - JComboBox 获取项目

c# - C#.net 中的正则表达式