问题
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"
回答1:
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
回答2:
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
来源:https://stackoverflow.com/questions/39007246/regex-for-matching-string-not-ending-or-containing-file-extensions