How can I make the regex not accept some values?

I want my regex to match some meanings, but not accept others. Basic regex ^/.+/.+$

I want not to accept the question mark in the last part / and not accept people or dungen as the first part / .

 MATCH: /a/b/c/d MATCH: /a/b NO MATCH: /people/b/c/d MATCH: /peoples/b/c/d NO MATCH: /a/b/c?x=y 

I know that you can use [^ABCD] to NOT match characters, but it will not work with whole lines.

Any help?

+4
source share
2 answers

Reject question marks after last / easy - use character class [^?] Instead . :

 ^/.+/[^?]+$ 

To reject people or dungen between two / s, you can use a negative scan . Since you want to reject /people/ but accept /peoples/ , the lookahead will look to the end of the line.

 ^/(?!(?:people|dungen)/.+$).+/.+$ 

Thus, the union of the two:

 ^/(?!(?:people|dungen)/[^?]+$).+/[^?]+$ 

Let the test.

 >>> import re >>> r = re.compile(r'^/(?!(?:people|dungen)/[^?]+$).+/[^?]+$') >>> for s in ['/a/b/c/d', '/a/b', '/people/b/c/d', '/peoples/b/c/d', '/a/b/c?x=y']: ... print not not r.search(s) ... True True False True False 
+4
source

you can use

 ^/(?!(people|dungen)/).+/[^?]+$ 
+1
source

All Articles