Java 中匹配 URL 的正则表达式 [英] Regular expression to match URLs in Java

查看:142
本文介绍了Java 中匹配 URL 的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在处理正则表达式时使用 RegexBuddy.我从它的库中复制了正则表达式以匹配 URL.我在 RegexBuddy 中测试成功.但是,当我将其复制为 Java String 风格并将其粘贴到 Java 代码中时,它不起作用.以下类打印 false:

I use RegexBuddy while working with regular expressions. From its library I copied the regular expression to match URLs. I tested successfully within RegexBuddy. However, when I copied it as Java String flavor and pasted it into Java code, it does not work. The following class prints false:

public class RegexFoo {

    public static void main(String[] args) {
        String regex = "\b(https?|ftp|file)://[-A-Z0-9+&@#/%?=~_|!:,.;]*[-A-Z0-9+&@#/%=~_|]";
        String text = "http://google.com";
        System.out.println(IsMatch(text,regex));
}

    private static boolean IsMatch(String s, String pattern) {
        try {
            Pattern patt = Pattern.compile(pattern);
            Matcher matcher = patt.matcher(s);
            return matcher.matches();
        } catch (RuntimeException e) {
        return false;
    }       
}   
}

有人知道我做错了什么吗?

Does anyone know what I am doing wrong?

推荐答案

请改用以下正则表达式字符串.您的测试可能以区分大小写的方式完成.我添加了小写字母以及适当的字符串开头占位符.

Try the following regex string instead. Your test was probably done in a case-sensitive manner. I have added the lowercase alphas as well as a proper string beginning placeholder.

String regex = "^(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]";

这也有效:

String regex = "\b(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]";

注意:

String regex = "<\b(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]>"; // matches <http://google.com>

String regex = "<^(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]>"; // does not match <http://google.com>

这篇关于Java 中匹配 URL 的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆