Reputation: 37
I am new to python, i am trying to search ad get all matched items from a list in python, however i am not getting if my input is case sensitive compared with List items.
The code which i am trying is below
# dl is available items in the list
dl=['AA_Food', 'FOOD_ORDER', 'AA_FOOD_APP', 'HOTPATH', 'FO_HOT', 'TEST_FOOD']
# search items
r = re.compile(".*FOO.*")
newlist = list(filter(r.match, dl)) # Read Note
nl = json.dumps(newlist)
print(nl)
I am getting the below result:
["FOOD_ORDER", "AA_FOOD_APP", "TEST_FOOD"]
But the expected result is:
["AA_Food", "FOOD_ORDER", "AA_FOOD_APP", "TEST_FOOD"]
please help.
Upvotes: 1
Views: 535
Reputation: 21
It may be because in the expression you have strictly defined FOO
to be uppercase. Try using (FOO|Foo)
in place of FOO
.
Hopefully, it works for you.
Upvotes: 2
Reputation: 677
I dont see why you need to use regular expressions. This can be done simply by using list comprehension
new_list = [item for item in dl if "foo" in item.lower()]
Upvotes: 2
Reputation: 500
Use re.IGNORECASE
for this
import re
# dl is available items in the list
dl=['AA_Food', 'FOOD_ORDER', 'AA_FOOD_APP', 'HOTPATH', 'FO_HOT', 'TEST_FOOD']
# search items
r = re.compile(".*FOO.*", re.IGNORECASE)
newlist = list(filter(r.match, dl)) # Read Note
print(newlist)
Upvotes: 5