Reputation: 822
here's my question.
I have a model with a list of regexp, say
|__Field_|
| (\w+) |
| ([op]+)|
| .* |
| others.|
i have a list of words, say ('cat', "dog", "wolf"), and i need to find which of the regexp stored in my model matches a word ( or multiple words ) in my list...
It's like an inverse __regexp filter.
How can i achieve this functionality?
Is there a better way to do something like that?
Thanks!
Upvotes: 2
Views: 901
Reputation: 1989
You didn't specified two important things:
Assuming you are using a database that allows performing queries using regex and your database supports the standard you need (PCRE/POSIX), you can inverse __regex
filter using the extra() Queryset modifier. Take a look at the code below:
Model.objects.extra(where=[sql_regex('REGEX_COLUMN')], params=['TEXT TO MATCH']).all()
Where the sql_regex()
code is something like:
from django.db import backend
def sql_regex(column, type='regex'):
op = backend.DatabaseWrapper.operators[type].replace('%s', column)
return '%s ' + op
I used backend.DatabaseWrapper.operators[type]
to get the predefined pattern to query regexes stored in database backends.
Upvotes: 3
Reputation: 30273
I highly doubt there's a "way" to do this, other than looping through each case, as @DrTyrsa comments.
I suppose you can make some optimizations though, if performance were a concern. For example, suppose many of your regexes had \w\w+
(i.e. words with two or more letters). You can check each word, e.g. "cat" or "1234" against just \w\w+
, and if the word doesn't match, then you don't have to bother to running the rest of your regexes, since they're all dependent on that one component.
Of course, the zero-accepting quantifiers ?
, *
, and {}
, and the alternation operator |
, makes this particular idea impossible, unless you regex your regexes to filter out ^[^?*{}]+$
. But now we're just getting ridiculous. It's already crazy that you'd need a sort of "regex hierarchy" to implement an "optimization" such as this. I think others can come up with more practical optimizations.
Good luck.
Upvotes: 1