1

I take this (?:([^:/?#]+):)?(?://([^/?#]*))?([^?#]*\. (?:jpg|gif|png))(?:\?([^#]*))?(?:#(.*))? regular expression from this answer. if i use this in my below program to match the url means i'm getting compiler error .

This is my code:

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");

}


}
Community
  • 1
  • 1

2 Answers2

2

You need to escape twice.

So replace \ with \\.

See it work

codaddict
  • 445,704
  • 82
  • 492
  • 529
0

The problem you have is that the backslash characters () in your regex are escape characters for Java, so it sees \. and \? and thinks your trying to escape a . and a ? - hence the compilation error that you're probably seeing talking about 'Invalid escape characters'.

To fix this, you need to escape the backslashes with their own backslashes. you get:

\\. and \\?

or, in full form:

(?:([^:/?#]+):)?(?://([^/?#]*))?([^?#]*\\.  (?:jpg|gif|png))(?:\\?([^#]*))?(?:#(.*))?
DaveyDaveDave
  • 9,821
  • 11
  • 64
  • 77