Java 将url与正则表达式匹配
我把这个Java 将url与正则表达式匹配,java,regex,Java,Regex,我把这个(?:([^:/?#]+):)(?:/([^/?#]*)([^?#]*)(?:jpg | gif | png))(?:\([^#]*)(?:#(.*)(?:#(.*))正则表达式从这里得到。如果我在下面的程序中使用这个来匹配url,意味着我得到了编译器错误 这是我的代码: public static void main(String[] args) { String url="http://justfuckinggoogleit.com/bart.gif"; matchesImageUr
(?:([^:/?#]+):)(?:/([^/?#]*)([^?#]*)(?:jpg | gif | png))(?:\([^#]*)(?:#(.*)(?:#(.*))
正则表达式从这里得到。如果我在下面的程序中使用这个来匹配url,意味着我得到了编译器错误
这是我的代码:
public static void main(String[] args) {
String url="http://justfuckinggoogleit.com/bart.gif";
matchesImageUrl(url);
}
public static void matchesImageUrl(String url){
Pattern imagePattern=Pattern.compile("(?:([^:/?#]+):)?(?://([^/?#]*))?([^?#]*\. (?:jpg|gif|png))(?:\?([^#]*))?(?:#(.*))?");
if(imagePattern.matcher(url).matches()){
System.out.println("image matches with the pattern" + url);
}
else{
System.out.println("image does not matches with the pattern");
}
}
你需要逃两次 因此,将
\
替换为\
您遇到的问题是正则表达式中的反斜杠()是Java的转义字符,因此它可以看到\。和\?并且认为你在试图逃避一场灾难。还有一个因此,您可能看到的编译错误是关于“无效转义字符” 要解决这个问题,您需要用反斜杠自己的反斜杠来逃避反斜杠。你会得到: \\。和\\ 或以完整形式:
(?:([^:/?#]+):)?(?://([^/?#]*))?([^?#]*\\. (?:jpg|gif|png))(?:\\?([^#]*))?(?:#(.*))?
如果可以的话,我会给你的表意文字+10的链接