Fundamentals 4 min read

Master Python Regex: How "+" and "*" Change Your Pattern Matching

This article explains the difference between the regex quantifiers "+" and "*" in Python, showing how each affects pattern matching through step‑by‑step examples and visual results.

Python Crawling & Data Mining
Python Crawling & Data Mining
Python Crawling & Data Mining
Master Python Regex: How "+" and "*" Change Your Pattern Matching

In this article we explore the difference between the regex quantifiers “+” and “*” in Python, illustrating how they affect pattern matching.

1. The “+” quantifier requires the preceding character to appear at least once; without it, a greedy pattern matches the shortest possible substring, resulting in “pp”.

2. Changing the pattern from ".*(p.*p).*" to ".*(p.+p).*" replaces “*” with “+”, forcing the characters between the two p’s to appear at least once. Running the program now yields “ppp”.

3. Replacing the three p’s with “php” and executing the same pattern produces the result “php”.

4. If the string is changed to “phhp”, the pattern still matches and returns “phhp”, because the “+” quantifier only requires at least one occurrence of the intermediate characters.

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

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-matchingasteriskplusquantifier
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.