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

Python正则表达式问题:精准筛选特定格式字符串并排除相似匹配项

How to Filter List Elements Matching the 'Test % result' Pattern with Python Regex?

Let's walk through how to solve this problem clearly. First, here's your original list for context:

l1 = ['Test 1 result', 'Test 2 result', 'Test 3 result', 'Test 1 grade result', 'other items', 'more items which will not have the same pattern']

Your goal is to extract only the items that follow the exact Test [number] result format, excluding entries with extra text (like grade) or unrelated content.

Solution 1: List Comprehension with re.match()

The most straightforward approach combines a list comprehension with a regex that enforces the exact pattern:

import re

# Define the source list
l1 = ['Test 1 result', 'Test 2 result', 'Test 3 result', 'Test 1 grade result', 'other items', 'more items which will not have the same pattern']

# Regex pattern breakdown:
# ^Test  : Matches the start of the string followed by "Test "
# \d+    : Matches one or more digits (works for single-digit like 1 or multi-digit like 10)
#  result$ : Matches " result" at the END of the string — this blocks extra text after the target phrase
pattern = r'^Test \d+ result$'

# Filter the list using the regex
l2 = [item for item in l1 if re.match(pattern, item)]

print(l2)
# Output: ['Test 1 result', 'Test 2 result', 'Test 3 result']

Solution 2: Using re.fullmatch() (Even Cleaner)

If you want a shorter pattern, re.fullmatch() automatically checks that the entire string matches the regex, so you don't need to add ^ and $ manually:

import re

l1 = ['Test 1 result', 'Test 2 result', 'Test 3 result', 'Test 1 grade result', 'other items', 'more items which will not have the same pattern']

pattern = r'Test \d+ result'
l2 = [item for item in l1 if re.fullmatch(pattern, item)]

print(l2)
# Same desired output as above

Key Regex Details

  • The ^ and $ (or fullmatch()) are critical: they ensure we don't match strings like Test 1 grade result, since that entry doesn't end with result.
  • If your test identifiers might include letters/underscores instead of just digits, replace \d+ with \w+ (which matches alphanumeric characters and underscores). For your specific example, \d+ is the most precise choice.
  • If you only need to match single-digit numbers, swap \d+ for \d.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 17:22:30