-2

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?

Melody
  • 1

3 Answers3

0

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

Source

Community
  • 1
  • 1
Francesco
  • 4,052
  • 2
  • 21
  • 29
0

* 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

rock321987
  • 10,942
  • 1
  • 30
  • 43
0
  • The + quantifier selects the preceding character 1 or more times, as many times as possible
  • The * quantifier selects the preceding character 0 or 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 <code>+</code>

Using the RegEx foo\d*bar (with a *):

foo1bar     # Match
foo234bar   # Match
foobar      # Match

Using <code>*</code>


A quote from the Python Docs on re:

  • + - 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 bs; it will not match just a
  • * - 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 bs
Kaspar Lee
  • 5,446
  • 4
  • 31
  • 54