我在使用正则表达式时使用 RegexBuddy。我从它的库中复制了正则表达式以匹配 URL。我在 RegexBuddy 中成功测试。但是,当我将它复制为 Java String
风格并将其粘贴到 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;
}
}
}
有谁知道我做错了什么?
最佳答案
改用以下正则表达式字符串。您的测试可能是以区分大小写的方式完成的。我添加了小写字母以及正确的字符串开头占位符。
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 - Java中匹配URL的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/163360/