tags:

views:

23

answers:

1

I had requirement where user should add only specific type of links as part of the attachments. For example, if user wants to upload file of type pdf, the url should end with .pdf similarly for document it should be .doc

To check this scenario I had written JUnit test as below

String url="ar.jpg";
String pm="(.*?)\\.(jpg|jpeg|png|gif)$";
Pattern p = Pattern.compile("pm");
Matcher m = p.matcher(url);     
System.out.println("-----exp  "+m.matches());

This test is always returning false.

Is there something wrong with my Pattern.

+3  A: 

You have a misprint - "pm" string is passed to compile() method, but pm variable must be passed:

String pm="(.*?)\\.(jpg|jpeg|png|gif)$";
Pattern p = Pattern.compile(pm); // <- here
Kel
Good catch..Is there anything to be modified as far as string pm is conserned.I mean...does it fits into any kind of URl which ends with jpg,jpeg etc..
GustlyWind
I don't see any problems in regexp itself - it should work for all strings which end with ".jpg", ".jpeg", ".png", ".gif".
Kel
Can I know what is the exact file extension here using another regular expression.
GustlyWind
You can do it, for example, in the following way: String[] urlArray = url.split("\."); String extension = urlArray[urlArray.length - 1];
Kel
Also, you may take a look at Matcher.group() function (http://download.oracle.com/javase/1.4.2/docs/api/java/util/regex/Matcher.html#group()) - it returns matched substring. In this case you will need regexp, which includes only extension check.
Kel
Thanks a ton....
GustlyWind