如何用Regex从字符串列表中精准筛选1-30编号条目
Filter Numbered Entries (1-30) Precisely
Your current regex approach is too broad—matching any word character first, then any leading digits—so it’s picking up dates or other numeric entries that don’t fit your "1-30. Title" format. Let’s fix this with a targeted regex that enforces both the number range and exact structure.
Step 1: Use a Precise Regex Pattern
We need a pattern that:
- Starts with a number between 1 and 30
- Followed immediately by a dot and a space (
.\) - Then includes the rest of the title text
Here’s the regex:
r'^(30|[1-2]\d|[1-9])\.\s.+$'
Breakdown:
^: Anchors the match to the start of the string(30|[1-2]\d|[1-9]): Matches valid numbers: 30, 10-29 ([1-2]\d), or 1-9 ([1-9])\.\s: Exact match for a dot followed by a space.+$: Captures the rest of the title text (one or more characters until the end of the string)
Step 2: Implement the Filter
Replace your two filter steps with a single, precise check:
import re # Compile the regex once for efficiency pattern = re.compile(r'^(30|[1-2]\d|[1-9])\.\s.+$') # Filter your list filtered_quotes = list(filter(pattern.match, quoteTitle))
Optional: Sort from 30 to 1
If you want the filtered entries sorted in descending order (30 first, 1 last), add this sorting step:
# Sort by the leading number, reversed sorted_quotes = sorted(filtered_quotes, key=lambda x: int(re.match(r'^\d+', x).group()), reverse=True)
This will eliminate any dates (like 2024. 05.20) or out-of-range numbers (like 31. Extra Entry) while keeping exactly the entries you want.
内容的提问来源于stack exchange,提问作者Tyler Estes
相关产品推荐
相关产品推荐

