[英]python regex match string does not start with
I want to match any string that does not start with 4321 I came about it with the positive condition: match any string that starts with 4321: 我希望匹配任何不以4321开头的字符串我带来了积极的条件:匹配任何以4321开头的字符串:
^4321.*
Now I want to reverse that condition, for example: 现在我想扭转这种状况,例如:
1234555
passes 1234555
通过 12322222
passess 12322222
None
passess None
过路 4321ZZZ
does not pass 4321ZZZ
不通过 43211111
does not pass 43211111
没有通过 Please help me find the simplest regex as possible that accomplishes this. 请帮助我找到最简单的正则表达式,以实现这一目标。
I am using a mongo regex but the regex object is build in python so please no python code here (like startswith
) 我正在使用mongo正则表达式,但正则表达式对象是在python中构建所以请在这里没有python代码(如
startswith
)
You could use a negative look-ahead (needs a multiline modifier): 您可以使用负前瞻(需要多线修改器):
^(?!4321).*
You can also use a negative look-behind (doesn't match empty string for now): 你也可以使用负面的后卫(现在不匹配空字符串):
(^.{1,3}$|^.{4}(?<!4321).*)
Note: like another answer stated, regex is not required (but is given since this was the question verbatim) -> instead just use if not mystring.startswith('4321')
. 注意:像另一个答案所说的那样,正则表达式不是必需的(但是由于这是逐字的问题而给出) - >只是使用
if not mystring.startswith('4321')
。
Edit: I see you are explicitly asking for a regex now so take my first one it's the shortest I could come up with ;) 编辑:我看到你现在明确要求正则表达式,所以拿我的第一个它是我能想到的最短的;)
You don't need a regex for that. 你不需要正则表达式。 Just use
not
and the startswith()
method: 只需使用
not
和startswith()
方法:
if not mystring.startswith('4321'):
You can even just slice it and compare equality: 你甚至可以将它切片并比较相等:
if mystring[:4] != '4321':
Why don't you match the string, and negate the boolean value using not
: 为什么不匹配字符串,并使用
not
否定布尔值:
import re
result = re.match('^4321.*', value)
if not result:
print('no match!')
Thank, @idos. 谢谢@idos。 For a complete answer I used the
mongo's
$or opertator 对于完整的答案,我使用了
mongo's
$或opertator
mongo_filter = {'$or': [{'db_field': re.compile("^(?!4321).*$")}, {'db_field1': {'$exists': False}}]})
This ensure not only strings that starts with 4321 but also if the field does not exists or is None
这不仅可以确保以4321开头的字符串,还可以确保字段不存在或者为
None
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.