用于标注序数词的正则表达式:Python doctest匹配难题求解
Hey fellow dev, I feel your pain—regex and doctests can be such a tricky combo, especially when one stubborn case refuses to play nice even after trying multiple pattern approaches. Let’s break down some tried-and-true fixes and patterns that often resolve these edge cases:
Common Doctest Output Gotchas & Fixes
- Whitespace inconsistencies: Doctests are notoriously picky about newlines, indentation, and trailing spaces. Ditch hardcoded spaces for flexible patterns:
- Use
\s+for one or more whitespace characters - Add the
re.DOTALLflag (or inline(?s)) to let.match newlines for multi-line outputs - Example for a multi-line result:
import re # Matches a section with "Result:" followed by any content (including newlines) pattern = r'(?s)Result:\s*(.*)'
- Use
- Dynamic values: If your doctest includes memory addresses, timestamps, or random numbers, target those with specific wildcards:
- Hex memory addresses:
0x[a-fA-F0-9]+ - Integers/floats:
\d+(\.\d+)? - Example to match a dynamic object reference:
pattern = r'<User object at 0x[a-fA-F0-9]+>'
- Hex memory addresses:
- Special regex characters: Escape any
.,*,?, or parentheses that appear in your static doctest output usingre.escape()to avoid accidental regex behavior:static_msg = "Error: Invalid input (value too large!)" # Escape the static part, then add a pattern for a dynamic error code pattern = re.escape(static_msg) + r'\s*Error code: (\d+)'
Example: Fixing a "Identical but Mismatched" Case
If your failing test looks like the outputs are identical but the regex still doesn’t match, it’s almost always whitespace. For example, if your doctest expects [1, 2, 3] but the actual output has subtle spacing differences, use this flexible pattern:
pattern = r'^\s*\[\s*1\s*,\s*2\s*,\s*3\s*\]\s*$'
Another pro tip: Build your regex incrementally. Start by matching the most static parts of the output, test that, then add patterns for dynamic sections one by one. Use re.match() or re.findall() to test each step and narrow down exactly where the mismatch is happening.
内容的提问来源于stack exchange,提问作者Ovaflow

