0

In a Java application, I need to write a String containing a regex for URIs, so that the URI does not contains character sequences like .js?, .css? and .jpg?, but are also not ending with .js, .css and .jpg

I made the following:

(?:.js|.css|.jpg)$|(?:.js[?]|.html[?]|.jpg[?])

Which basically matches all the URIs ending with the given file extensions or containing the file extension plus the question mark.

How can I do the negation of the and of the previous conditions?

So, for instance I expect that the following URI will match

"/a/fancy/uri/.js/which/is/valid"

but both the following will not

"/a/fancy/uri/which/is/invalid.js"
"/a/fancy/uri/which/is/invalid.js?ver=1"
mat_boy
  • 12,998
  • 22
  • 72
  • 116

2 Answers2

5

Use two alternations in a negative look ahead:

^(?!.*\.(js|css|jpg)($|\?)).*

This regex matches valid input. In java:

if (url.matches("^(?!.*\\.(js|css|jpg)($|\\?)).*")
    // url is OK

If you want to match invalid input, use a positive look ahead:

if (url.matches("^(?=.*\\.(js|css|jpg)($|\\?)).*")
    // url is not OK
Bohemian
  • 412,405
  • 93
  • 575
  • 722
  • 1
    Perfect! I'm using it in combination with this [answer](http://stackoverflow.com/a/37578136/1983997) on how to use placeholders in Spring controllers – mat_boy Aug 18 '16 at 06:04
1

If you're trying match invalid URLs, this should do it:

String regex = ".*\\.(js|css|jpg)($|\\?.*)";
System.out.println("/a/fancy/uri/which/is/invalid.js?ver=1".matches(regex));
System.out.println("/a/fancy/uri/which/is/invalid.js".matches(regex));
System.out.println("/a/fancy/uri/.js/which/is/valid".matches(regex));

Output:

true
true
false
shmosel
  • 49,289
  • 6
  • 73
  • 138
  • I'd like to match if the url is valid, so for instance has not to end with .css or has not to contains .css? – mat_boy Aug 18 '16 at 06:00