Guy Bowden
Guy Bowden

Reputation: 5107

Regex for everything except certain matches

I'm trying to create a redirect regex script that will forward the user onto another domain with the path intact, except when the path matches something specific.

i.e.

http://www.a.com/anything/foo/bar -> http:www.b.com/anything/foo/bar

but if the path starts with something special, then don't redirect:

http://www.a.com/special/1/2/3 -> no redirect

My redirect app works like this: I put entries in line by line (this works fine):

"^/(?P<path>[-\w]+)/(?P<foo>[-\w]+)/(?P<bar>[-\w]+)/$","%(path)s/%(bar)s/%(foo)s/"
"^/(?P<path>.*)$","http://www.b.com/%(path)s"

So something like this (doesn't work):

"^/(?P<path>!(special).*)$","http://www.b.com/%(path)s"

Upvotes: 0

Views: 296

Answers (2)

Aram Kocharyan
Aram Kocharyan

Reputation: 20431

http://www.a.com/(?!special).* will match anything which starts with http://www.a.com/ but not http://www.a.com/special.

Upvotes: 2

Martijn Pieters
Martijn Pieters

Reputation: 1121914

You are looking for a negative lookahead:

"^/(?P<path>(?!special/).*)$","http://www.b.com/%(path)s"

The (?!...) syntax means:

(?!...)
Matches if ... doesn’t match next. This is a negative lookahead assertion. For example, Isaac (?!Asimov) will match 'Isaac ' only if it’s not followed by 'Asimov'.

so the expression matches if the path starts with / but is not followed by special/.

Demo:

>>> import re
>>> re.search(r"^/(?P<path>(?!special/).*)$", '/special/path') is None
True
>>> re.search(r"^/(?P<path>(?!special/).*)$", '/not-so-special/path').groupdict()
{'path': 'not-so-special/path'}

Upvotes: 1

Related Questions