如何让正则表达式不接受某些值?

时间:2022-11-25 11:21:26

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.

我想不接受最后/部分中的问题标记,不接受人或dungen作为第一部分。

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.

我知道你可以使用[^ ABCD]来匹配字符,但它不适用于整个字符串。

Any help?

2 个解决方案

#1


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.

要拒绝两者之间的人或者dungen,你可以使用负向前瞻。既然你想拒绝/ people /但是接受/ peoples / the lookahead一直看到字符串的结尾。

^/(?!(?: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

#2


1  

You could use

你可以用

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

#1


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.

要拒绝两者之间的人或者dungen,你可以使用负向前瞻。既然你想拒绝/ people /但是接受/ peoples / the lookahead一直看到字符串的结尾。

^/(?!(?: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

#2


1  

You could use

你可以用

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