2016-08-08 30 views
1

匹配我有一個名單,我想列表中的每個元素與之比較的正則表達式的列表,然後僅打印不發現regex.Regex從一個配置文件來了:的Python:正則表達式的元素與列表

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

代碼:

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 

我能夠逐一打印regexs,但如何比較針對列表regexs。

+0

我懷疑這些是通配符模式,而不是正則表達式模式。 –

回答

1

而不是使用重新模塊,我將用的fnmatch模塊,因爲它看起來像的通配符匹配。

請查看此鏈接瞭解更多關於fnmatch的信息。

擴展您的代碼所需的輸出:

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 

輸出:

C:\Users>python main.py 
quit 
quest 

請讓我知道,如果它是有幫助的。

+1

非常感謝,它按預期工作。 – cloudvar