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 morei'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 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.
* 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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With