You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

列表按索引比对元素时忽略模式字符串中动态内容的实现方案

实现逻辑说明

首先做两层校验:

  • 第一步先校验两个列表长度是否完全一致,长度不等直接返回False
  • 第二步逐索引比对两个列表的对应元素:
    1. 把模式元素中所有<任意内容>的片段替换为正则通配符,同时转义模式中的其他正则特殊字符,避免意外匹配
    2. 用生成的正则去匹配对应位置的待校验字符串,只要有一个位置不匹配就直接返回False
  • 所有位置都匹配通过则返回True
代码实现(Python示例)
import re

def match_list(pattern: list[str], check_list: list[str]) -> bool:
    # 长度不一致直接判定不匹配
    if len(pattern) != len(check_list):
        return False
    
    for pat_str, check_str in zip(pattern, check_list):
        # 拆分模式中的固定内容和动态占位部分
        parts = re.split(r'(<[^>]+>)', pat_str)
        regex_parts = []
        for part in parts:
            if part.startswith('<') and part.endswith('>'):
                # 动态占位部分替换为任意字符匹配规则
                regex_parts.append(r'.*?')
            else:
                # 固定内容部分转义正则特殊字符,避免误匹配
                regex_parts.append(re.escape(part))
        # 拼接完整正则,添加前后锚定保证全字符串匹配
        regex = re.compile('^' + ''.join(regex_parts) + '$')
        if not regex.match(check_str):
            return False
    return True
测试用例验证
# 第一个示例测试
pattern1 = ['Hi', 'my' , 'name is <xxxxxxxxxxx> age <yy>']
list2 = ['Hi', 'my' , 'name is soku age 21']
list3 = ['Hi', 'my', 'soku']
print(match_list(pattern1, list2)) # 输出 True
print(match_list(pattern1, list3)) # 输出 False

# 第二个示例测试
pattern2 = ['A', 'B', 'C_<xxxx>_AB']
list1 = ['A', 'B', 'C_aaaa112=22_AB']
print(match_list(pattern2, list1)) # 输出 True

内容的提问来源于stack exchange,提问作者SoKu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 08:24:08