Master Python Regex: Using Curly Braces {} for Precise Pattern Matching
This article explains how Python’s regular expression quantifier “{}” works, detailing its three forms—{n}, {n,}, and {n,m}—and demonstrates each with clear examples and visual illustrations to help readers master precise pattern matching.
Today we continue sharing basic knowledge of Python regular expressions, focusing on the special character "{}".
The "{}" character acts as a quantifier that limits the number of occurrences of the preceding element. It has three common forms: "{n}", "{n,}", and "{n,m}". For example, "{1}", "{1,}", and "{1,3}".
Examples:
1. Limiting the preceding character to appear exactly once. Using a greedy match, the pattern "p.{1}p" matches "pap".
2. Changing the pattern to ".*(p.{2}p).*" yields no output because no substring satisfies the condition.
3. Modifying the original string allows the pattern ".*(p.{2}p).*" to produce a match.
4. The quantifier "{1,}" means the preceding character appears at least once; "{2,}" means at least twice; "{3,}" means at least three times, and so on.
5. The quantifier "{1,3}" means the preceding character appears between one and three times inclusive; similarly "{2,5}" means between two and five times.
In greedy mode, the engine scans from right to left; for the pattern with "{1,3}", the substring "phhhhp" (four occurrences) is rejected, and the engine continues to find "paap", which satisfies the condition.
6. Using "{3,5}" yields the match "phhhhp".
Did you get the usage of the special character "{}" in regular expressions?
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Python Crawling & Data Mining
Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
