简体   繁体   中英

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.

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.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM