Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 将url与正则表达式匹配_Java_Regex - Fatal编程技术网

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的链接