I am trying a make a regex query on django query set. I have a column having values like
'67,42,16', '16,42,67,70', '4,11,21,78', '12,45,6,22'
I want to extract columns having either '4' or '70' in them. Here is my regex
_regex = r"(^|(\d*,)+)%s((,\d*)+|$)" %('4|70')
and my query
dict(Table.objects.filter(column__regex=_regex).values_list('row_id','column'))
Its returning the following result
{1563864L: u'67,42,16', 1563804L: u'16,42,67,70', 1563863L: u'4,11,21,78'}
I am expecting this result 1563804L: u'16,42,67,70', 1563863L: u'4,11,21,78'
Not sure why I am getting 1563864L: u'67,42,16'
as a result
Any help will be appreciated. Thanks in advance
I can only guess what you're trying to do, as it's always difficult to reverse a regular expression's original intent. Try this.
_regex = '(^({0}),.+)|(.+,({0}),.+)|(.+,({0})$)'.format('4|70')
And a little more pythonic:
acceptable_values = [4, 70]
regex_template = '(^({0}),.+)|(.+,({0}),.+)|(.+,({0})$)'
_regex = regex_template.format('|'.join([str(v) for v in acceptable_values]))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.