普通EX pression匹配的字符串(1+字符)并没有在.EXT结束(扩展)并没有、字符串、字符、结束

2023-09-03 10:08:56 作者:寂寞成影

我需要测试一个URL,它的不结束与的.asp

I need to test a url that it does not end with .asp

所以测试的test.html Test.aspx的应该匹配,但 TEST.ASP 应该不能比拟的。

So test, test.html and test.aspx should match, but test.asp should not match.

通常你会测试该URL的确实结束以.asp,并否认它进行匹配使用NOT运算符code的事实:

Normally you'd test if the url does end with .asp and negate the fact that it matched using the NOT operator in code:

if(!regex.IsMatch(url)) { // Do something }

在这种情况下,常规的前pression将 \。ASP $ 但在这种情况下,我需要经常EX pression导致比赛。

In that case the regular expression would be \.asp$ but in this case I need the regular expression to result in a match.

背景:我需要使用常规EX pression作为路由约束实现的ASP.NET MVC RouteCollection.MapRoute 扩展方法。这条路线需要匹配所有控制器,但是当在URL中的控制器以.asp结尾应该告吹

Background: I need to use the regular expression as a route contraint in the ASP.NET MVC RouteCollection.MapRoute extension method. The route needs to match all controllers but it should fall through when the controller in the url ends with .asp

推荐答案

的技巧是使用负后向。

如果你只需要一个是/否的回答:

If you need just a yes/no answer:

(?<!\.asp)$

如果你需要匹配整个网址:

If you need to match the whole URL:

^.*(?<!\.asp)$

这些正则表达式将会与任何URL工作所在的文件名出现在URL的末尾(即网址没有查询或片段)。我假设你的URL适应这种限制给你的问题​​,正则表达式的.asp $。如果你想用所有的URL工作,试试这个:

These regexes will work with any URL where the file name occurs at the end of the URL (i.e. URLs without a query or fragment). I'm assuming your URLs fit this limitation given the regex .asp$ in your question. If you want it to work with all URLs, try this:

^[^#?]+(?<!\.asp)([#?]|$)

或者这样,如果你想在正则表达式匹配整个网址:

Or this if you want the regex to match the whole URL:

^[^#?]+(?<!\.asp)([#?].+|$)