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.
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 '+'.
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.
