I'm pretty new to RE. What is the difference between "*" and "+"? They all seem to indicate equal the preceding element zero or more times, as much as possible?
3 Answers
+ means one or more times, while * is zero or more times
"*" Causes the resulting RE to match 0 or more repetitions of the preceding RE, as many repetitions as are possible. ab* will match ‘a’, ‘ab’, or ‘a’ followed by any number of ‘b’s.
'+' Causes the resulting RE to match 1 or more repetitions of the preceding RE. ab+ will match ‘a’ followed by any non-zero number of ‘b’s; it will not match just ‘a’.
* matches 0 or more times. It is successful even if there is no match. So a* will be successful even in the string bcd
+ matches 1 or more times. There should be at least one match, then only its successful. If we use a+, then there should be at least one a present for successful match. So it will fail for the string bcd
Both of * and + are greedy in nature so they will match as much as possible before terminating or backtracking
- 10,942
- 1
- 30
- 43
- The
+quantifier selects the preceding character1or more times, as many times as possible - The
*quantifier selects the preceding character0or more times, as many times as possible
Examples
Using the RegEx foo\d+bar (with a +):
foo1bar # Match
foo234bar # Match
foobar # Not a Match
Using the RegEx foo\d*bar (with a *):
foo1bar # Match
foo234bar # Match
foobar # Match
A quote from the Python Docs on re:
+- Causes the resulting RE to match1or more repetitions of the preceding RE.ab+will matchafollowed by any non-zero number ofbs; it will not match justa*- Causes the resulting RE to match0or more repetitions of the preceding RE, as many repetitions as are possible.ab*will matcha,ab, orafollowed by any number ofbs
- 5,446
- 4
- 31
- 54

