gpt4 book ai didi

Python:正则表达式元素与列表匹配

转载 作者:太空宇宙 更新时间:2023-11-03 16:17:21 29 4
gpt4 key购买 nike

我有一个列表,我想将列表中的每个元素与正则表达式列表进行比较,然后仅打印正则表达式未找到的内容。正则表达式来自配置文件:

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

我可以一一打印正则表达式,但如何将正则表达式与列表进行比较。

最佳答案

我将使用 fnmatch 模块,而不是使用 re 模块,因为它看起来像通配符模式匹配。

请查看此链接以获取有关 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

如果有帮助,请告诉我。

关于Python:正则表达式元素与列表匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38835193/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com