Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between * and + in python regex?

Tags:

python

regex

I am quite new to python and practicing a few regular expression from google python exercies A section from there says :

Repetition

Things get more interesting when you use + and * to specify repetition in the pattern

+ -- 1 or more occurrences of the pattern to its left, e.g. i+ = one or more i's

* -- 0 or more occurrences of the pattern to its left

So I decided to try out some samples .

import re
text="xx1  2   3xx"
match = re.search(r'\d\s+\d\s+\d',text)
match.group()

and this yields the following output :

1  2   3

and to understand the difference between * and + I tried this :

import re
text="xx1  2   3xx"
match = re.search(r'\d\s*\d\s*\d',text)
match.group()

and yielded the output :

1  2   3

(the same as output 1)

I still wonder,whether these : * and + really have same function? If not examples are much appreciated!

Please correct me if I'm wrong somewhere.

like image 684
Diljit PR Avatar asked Mar 09 '26 14:03

Diljit PR


2 Answers

Like it says, * matches zero or more, + matches one or more. But you only tested them on a case where there is more than one space, which means they both apply. Compare how your regexes work on "xx12 3xx" where there are zero spaces between the first two digits.

like image 53
BrenBarn Avatar answered Mar 12 '26 02:03

BrenBarn


* matches 0 or more repetitions of the preceding RE, while + 1 or more repetitions of the preceding RE.

>>> re.findall(r'a\s*b', 'ab')
['ab']
>>> re.findall(r'a\s+b', 'ab')
[]

>>> re.findall(r'a\s*b', 'a b')
['a b']
>>> re.findall(r'a\s+b', 'a b')
['a b']
like image 30
falsetru Avatar answered Mar 12 '26 02:03

falsetru



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!