Search code examples
pythonregexfindallignore-case

python regex match case option


I would like to utilize a match case option. I have a piece of code to search a string in a list. I guess there is a more elegant way to do the same.

searchString = "maki"
itemList = ["Maki", "moki", "maki", "Muki", "Moki"]

resultList = []
matchCase = 0

for item in itemList:
    if matchCase:
        if re.findall(searchString, item):
            resultList.append(item)
    else:
        if re.findall(searchString, item, re.IGNORECASE):
            resultList.append(item)

I could use re.findall(searchString, item, flags = 2) because re.IGNORECASE basically an integer (2) but I don't know which number would mean "matchcase" option.


Solution

  • You can enforce the case insensitive search inside the comprehension:

    searchString = "maki"
    itemList = ["Maki", "moki", "maki", "Muki", "Moki"]
    
    resultList =[]
    matchCase = 1
    
    if matchCase:
        resultList = [x for x in itemList if x == searchString]
    else:
        resultList = [x for x in itemList if x.lower() == searchString.lower()]
    
    print resultList
    

    It will print ['maki'] if matchCase is 1, and ['Maki', 'maki'] if it is set to 0.

    See IDEONE demo