Fundamentals 4 min read

Master Python Regex: When '+' Beats '*' for Precise Matching

This article explains how Python’s regex quantifiers '+' and '*' differ, demonstrating with step‑by‑step examples how '+' requires at least one occurrence of the preceding character, while '*' allows zero or more, and shows the resulting matches through clear screenshots.

Python Crawling & Data Mining
Python Crawling & Data Mining
Python Crawling & Data Mining
Master Python Regex: When '+' Beats '*' for Precise Matching

1. The regex special character '+' means that the character(s) before it must appear at least once for a match to succeed. Without '+', the greedy mode matches from the right, resulting in "pp" as shown.

2. Changing the pattern from ".*(p.*p).*" to ".*(p.+p).*" replaces '*' with '+', requiring the preceding character to appear at least once. Running the program yields "ppp".

In simple terms, after matching the first 'p', the '+' quantifier forces the next characters to appear at least once before matching the second 'p', thus extracting the intended substring.

3. Replacing the three 'p's with "php" and running the program produces "php" as shown.

4. Changing "ppp" to "phhp" results in "phhp", confirming that '+' extracts any sequence where the preceding character appears at least once.

The '+' quantifier ensures that any character appearing at least once is captured.

5. In summary, both '*' and '+' are quantifiers that limit how many times the preceding character can appear. '*' allows zero or more occurrences, while '+' requires at least one occurrence.

Hopefully you now understand the difference between the regex quantifiers '*' and '+'.

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.

Pythonregular expressionsregexpattern-matchingquantifiers
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.