C# 匹配不以 .ext(扩展名)结尾的字符串(1+ 个字符)的正则表达式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/323697/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 23:13:28  来源:igfitidea点击:

Regular expression to match a string (1+ characters) that does NOT end in .ext (extension)

c#.netasp.net-mvcregex

提问by Michiel van Oosterhout

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

我需要测试一个不以结尾的网址.asp

So test, test.htmland test.aspxshould match, but test.aspshould not match.

所以test,test.htmltest.aspx应该匹配,但test.asp不应该匹配。

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

通常,您会测试 url是否以 .asp 结尾,并在代码中使用 NOT 运算符否定它匹配的事实:

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

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

在这种情况下,正则表达式将是,\.asp$但在这种情况下,我需要正则表达式来导致匹配。



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

背景:我需要在 ASP.NET MVCRouteCollection.MapRoute扩展方法中使用正则表达式作为路由约束。该路由需要匹配所有控制器,但当 url 中的控制器以 .asp 结尾时它应该会失败

采纳答案by Jan Goyvaerts

The trick is to use negative lookbehind.

诀窍是使用负面的lookbehind

If you need just a yes/no answer:

如果您只需要是/否答案:

(?<!\.asp)$

If you need to match the whole URL:

如果您需要匹配整个 URL:

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

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:

这些正则表达式适用于文件名出现在 URL 末尾的任何 URL(即没有查询或片段的 URL)。鉴于您的问题中的正则表达式 .asp$,我假设您的网址符合此限制。如果您希望它适用于所有 URL,请尝试以下操作:

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

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

或者,如果您希望正则表达式匹配整个 URL:

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

回答by Winston Smith

Try this

尝试这个

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

回答by inspite

Not a regexp, but c# String.EndsWith method which could easily do the job.

不是正则表达式,而是可以轻松完成这项工作的 c# String.EndsWith 方法。

ie

IE

string test1 = "me.asp" ;
string test2 = "me.aspx" ;

test1.EndsWith(".asp") // true;
test2.EndsWith(".asp") // false ;