最佳答案
我在使用正则表达式时使用 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;
}
}
}
有人知道我哪里做错了吗?