简体   繁体   English

Django 查询集中的正则表达式

[英]Regex in Django query set

I'm trying to write a Django query that will filter by a particular regex pattern.我正在尝试编写一个 Django 查询,它将按特定的正则表达式模式进行过滤。

I want to filter by a code that pulls out any cases where there's any non-digit character followed by a number, followed by a non-digit character (a white space is fine).我想通过一个代码进行过滤,该代码可以提取出任何非数字字符后跟一个数字,后跟一个非数字字符(空格很好)的情况。

Just say some codes are AJDP8EP, jsif28EP, EROE88, oskdpoeks8 .就说一些代码是AJDP8EP, jsif28EP, EROE88, oskdpoeks8

So I want my results to return: AJDP8EP, oskdpoeks8 .所以我希望我的结果返回: AJDP8EP, oskdpoeks8

This is my query, but it's not recognizing things properly.这是我的查询,但它不能正确识别事物。 Number is a variable.数字是一个变量。

results = Book.objects.filter(author__contains = firstname,type = "Fiction").filter(code__regex = r'^(\D+)(number)(\D+)')

You cannot use a variable inside your quoted regex expression. 您不能在引用的正则表达式中使用变量。 Try concatenating strings like: 尝试连接字符串,如:

r"^(\\D+)(" + str(number) + ")(\\D+)"

This converts your number variable to a string in case it is not already. 这会将您的number变量转换为字符串,以防它已经存在。

Also, as indicated in one of the comments to your question, oskdpoeks8 will not match your pattern. 另外,如您对问题的评论之一所示, oskdpoeks8将与您的模式不匹配。 If you want to catch cases where number may come at the end of the code, one solution would be: 如果你想捕到代码末尾可能出现number情况,一个解决方案是:

r"^(\\D+)(" + str(number) + ")(\\D*)"

Note the replacement of the + with an * to catch that case of zero occurrences. 注意用*替换+以捕获零次出现的情况。

With python 3+ you can make use of f-strings to pass variables to regex and use them in queries.使用 python 3+,您可以使用 f-strings 将变量传递给正则表达式并在查询中使用它们。 For example:例如:

Car.objects.filter(
    car_code=rf'^{settings.SOME_SETTING}0*(\d+)$'
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM