Skip to main content
 首页 » 编程设计

python之有什么比在循环中搜索每个子字符串更好的匹配字符串中多个子字符串的方法

2025年05月04日34shanyou

我正在使用 Python,我想将给定的字符串与多个子字符串匹配。我试图以两种不同的方式解决这个问题。我的第一个解决方案是将子字符串与如下字符串匹配:

str = "This is a test string from which I want to match multiple substrings" 
value = ["test", "match", "multiple", "ring"] 
temp = [] 
temp.extend([x.upper() for x in value if x.lower() in str.lower()]) 
print(temp) 

结果是 temp = ["TEST", "MATCH", "MULTIPLE", "RING"]。

然而,这不是我想要的结果。子字符串应完全匹配,因此“ring”不应与“string”匹配。

这就是为什么我尝试用正则表达式来解决这个问题,像这样:

str = "This is a test string from which I want to match multiple substrings" 
value = ["test", "match", "multiple", "ring"] 
temp = [] 
temp.extend([ 
    x.upper() for x in value 
    if regex.search( 
        r"\b" + regex.escape(x) + r"\b", str, regex.IGNORECASE 
    ) is not None 
]) 
print(temp) 

结果是 ["TEST", "MATCH", "MULTIPLE"],正确的解决方案。

尽管如此,此解决方案的计算时间过长。我必须对大约 100 万个字符串进行此检查,与使用第一个解决方案所需的 1.5 小时相比,使用正则表达式的解决方案需要数天才能完成。

有没有办法让第一个解决方案起作用,或者使第二个解决方案运行得更快?

value 也可以包含数字,或者像“test1 test2”这样的短语。

请您参考如下方法:

在没有看到实际数据的情况下很难提出最佳解决方案,但您可以尝试以下操作:

  • 生成匹配所有值的单个模式。这样您只需搜索一次字符串(而不是每个值一次)。
  • 跳过转义值,除非它们包含特殊字符(如 '^' 或 '*')。
  • 使用列表理解创建结果列表,而不是重复调用 list.extend()。
# 'str' is a built-in function, so use another name instead 
string = 'A Test test string from which I want to match multiple substrings' 
values = ['test', 'test2', 'Multiple', 'ring', 'match'] 
pattern = r'\b({})\b'.format('|'.join(map(re.escape, values))) 
 
# unique matches, uppercased 
matches = set(map(str.upper, re.findall(pattern, string, regex.IGNORECASE))) 
 
# arrange the results as they appear in `values` 
matched_values = [v for value in values if (v := value.upper()) in matches] 
print(matched_values)  # ['TEST', 'MULTIPLE', 'MATCH']