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