将url与正则表达式匹配

时间:2011-11-03 13:07:17

标签: java regex

我从此answer获取此(?:([^:/?#]+):)?(?://([^/?#]*))?([^?#]*\. (?: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");

}


}

2 个答案:

答案 0 :(得分:2)

你需要逃脱两次。

所以用\替换\\

See it work

答案 1 :(得分:0)

你遇到的问题是你的正则表达式中的反斜杠字符()是Java的转义字符,因此它看到\。和\?并认为你试图逃避一个。和一个? - 因此编译错误,你可能会看到'无效的转义字符'。

要解决此问题,您需要使用自己的反斜杠转义反斜杠。你得到:

\\。和\\?

或者,完整形式:

(?:([^:/?#]+):)?(?://([^/?#]*))?([^?#]*\\.  (?:jpg|gif|png))(?:\\?([^#]*))?(?:#(.*))?
相关问题