正则表达式以匹配Java中的URL

时间:2020-03-06 15:02:11  来源:igfitidea点击:

在使用正则表达式时,我使用RegexBuddy。我从其库中复制了正则表达式以匹配URL。我在RegexBuddy中成功测试。但是,当我将其复制为JavaString风格并将其粘贴到Java代码中时,它将无法正常工作。下面的类输出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;
    }       
}   
}

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

解决方案

请尝试以下正则表达式字符串。测试可能以区分大小写的方式进行。我添加了小写字母Alpha以及正确的字符串开头占位符。

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.net.URL

URL url = new URL(stringURL);

如果无法解析网址,则上面的代码将抛出MalformedURLException

这也适用:

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>

因此,第一个可能更适合常规使用。

使用RegexBuddy库的正则表达式时,请确保在我们自己的代码中使用与库中的regex相同的匹配模式。如果在"使用"选项卡上生成源代码片段,则RegexBuddy将自动在源代码片段中设置正确的匹配选项。如果我们复制/粘贴正则表达式,则必须自己做。

正如其他人指出的,在这种情况下,我们错过了不区分大小写的选项。