Regex for matching string not ending or containing file extensions

守給你的承諾、 提交于 2019-12-08 09:45:38

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!