4

I want my regex to match some values, but not accept others. The base regex is ^/.+/.+$

I want to not accept questions 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 you can use [^ABCD] in order to NOT match characters, but it won't work with whole strings.

Any help?

2 Answers 2

4

Rejecting question marks after the last / is easy - use a character class [^?] instead of .:

^/.+/[^?]+$

To reject people or dungen in between the two /s, you can use negative lookahead. Since you want to reject /people/ but accept /peoples/ the lookahead looks all the way to the end of the string.

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

So combining the two:

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

Let's 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
Sign up to request clarification or add additional context in comments.

Comments

1

You could use

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.