tomarv2
tomarv2

Reputation: 823

Python: regex elements match with List

I have a list, I want to compare each element of list against a list of regex and then print only what is not found with regex.Regex are coming from a config file:

exclude_reg_list= qa*,bar.*,qu*x

Code:

import re
read_config1 = open("config.ini", "r")
for line1 in read_config1:
    if re.match("exclude_reg_list", line1):
         exc_reg_list = re.split("= |,", line1)
         l = exc_reg_list.pop(0)
         for item in exc_reg_list:
             print item

I am able to print the regexs one by one, but how to compare regexs against the list.

Upvotes: 1

Views: 220

Answers (1)

Dinesh Pundkar
Dinesh Pundkar

Reputation: 4196

Instead of using re module, I am going to use fnmatch module since it looks like wildcard pattern matching.

Please check this link for more information on fnmatch.

Extending your code for desired output :

import fnmatch
exc_reg_list = []

#List of words for checking
check_word_list = ["qart","bar.txt","quit","quest","qudx"]

read_config1 = open("config.ini", "r")
for line1 in read_config1:
    if re.match("exclude_reg_list", line1):
        exc_reg_list = re.split("= |,", line1)

        #exclude_reg_list= qa*,bar.*,qu*x
        for word in check_word_list:
            found = 0
            for regex in exc_reg_list:
               if fnmatch.fnmatch(word,regex):
                    found = 1
            if found == 0:
                   print word 

Output:

C:\Users>python main.py
quit
quest

Please let me know if it is helpful.

Upvotes: 1

Related Questions