Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Regex: How detect a URL with file extension

How create a REGEX to detect if a "String url" contains a file extension (.pdf,.jpeg,.asp,.cfm...) ?

Valids (without extensions):

  • http://www.yahoo.com
  • http://dbpedia.org/ontology/
  • http://www.rdf.com.br

Invalids (with extensions):

  • http://www.thesis.com/paper.pdf
  • http://pics.co.uk/mypic.png
  • http://jpeg.com/images/cool/the_image.JPEG

Thanks, Celso

like image 920
celsowm Avatar asked Mar 03 '11 22:03

celsowm


2 Answers

In Java, you are better off using String.endsWith() This is faster and easier to read. Example:

"file.jpg".endsWith(".jpg") == true
like image 199
Amir Raminfar Avatar answered Sep 23 '22 14:09

Amir Raminfar


Alternative version without regexp but using, the URI class:

import java.net.*;

class IsFile { 
  public static void main( String ... args ) throws Exception { 
    URI u = new URI( args[0] );
    for( String ext : new String[] {".png", ".pdf", ".jpg", ".html"  } ) { 
      if( u.getPath().endsWith( ext ) ) { 
        System.out.println("Yeap");
        break;
      }
    }
  }
}

Works with:

java IsFile "http://download.oracle.com/javase/6/docs/api/java/net/URI.html#getPath()"
like image 29
OscarRyz Avatar answered Sep 26 '22 14:09

OscarRyz