Fundamentals 5 min read

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.

Python Crawling & Data Mining
Python Crawling & Data Mining
Python Crawling & Data Mining
Master Python Regex: Using Curly Braces {} for 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".

Example 1
Example 1

2. Changing the pattern to ".*(p.{2}p).*" yields no output because no substring satisfies the condition.

Example 2
Example 2

3. Modifying the original string allows the pattern ".*(p.{2}p).*" to produce a match.

Example 3
Example 3

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.

Example 4
Example 4

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.

Example 5
Example 5

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.

Example 6
Example 6

6. Using "{3,5}" yields the match "phhhhp".

Did you get the usage of the special character "{}" in regular expressions?

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Pythonregexpattern-matchingquantifier
Python Crawling & Data Mining
Written by

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!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.