开发者

How to ignore words in string using Regular Expressions

I need a piece of regex that can be used to do a NOT match. Take for example the following URL's

 http://www.site.com/layout/default.aspx
 http://www.site.com/default.aspx
 http://www.site.com/layout.aspx

The regex should NOT match any url string that 开发者_开发技巧contains the directory "layout"

http://www.site.com/layout/default.aspx

and instead should match on

http://www.site.com/default.aspx
http://www.site.com/layout.aspx

How can i do this using .NET regex?


Use negative lookahead:

^(?!.*/layout/)

You have to anchor to the start of the string or you'll get false positives i.e. (?!/layout/) alone won't work.


If you need to squeeze everything in one regex, try negative lookahead, something along the lines of this:

(?!layout)


Just match /layout/ and invert the result, whatever language you use.

E.g. with PHP:

if(!preg_match('#/layout/#i', $url)) {
    // does not match layout
}


PYTHON:

import re
if not re.match('layout'):
      #do whatever here

re is regex for python

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜