可以使用re模块中的re.match()函数来实现通配符表达式的匹配。先将通配符表达式转化为正则表达式,再使用re.match()函数进行匹配。

下面是一个示例代码:

import re

def wildcard_match(pattern, strings):
    # 将通配符表达式转化为正则表达式
    pattern = pattern.replace('.', '\\.').replace('*', '.*').replace('?', '.')
    # 编译正则表达式
    regex = re.compile(pattern, re.IGNORECASE)
    # 逐个匹配字符串
    results = []
    for string in strings:
        # 使用re.match()函数进行匹配
        if re.match(regex, string):
            results.append(True)
        else:
            results.append(False)
    return results

# 测试示例
pattern = '*.txt'
strings = ['file.txt', 'document.doc', 'picture.jpg']
results = wildcard_match(pattern, strings)
print(results)  # 输出: [True, False, False]

在上述示例中,通配符表达式*.txt被转化为正则表达式.*\.txt,其中.*表示匹配任意字符(0个或多个),\.表示匹配.字符,txt表示匹配字符串txt。然后使用re.match()函数逐个匹配字符串,如果匹配成功则将结果添加到结果列表中,并最终返回结果列表。由于使用了re.IGNORECASE参数,因此匹配时不区分大小写

输入:通配符表达式;一组字符串。输出:返回不区分大小写的匹配结果匹配成功输出true匹配失败输出false用python实现

原文地址: http://www.cveoy.top/t/topic/iZT2 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录