thatthatisis
thatthatisis

Reputation: 783

What's the meaning of *? in regular expressions?

I've run across some code several times that has a regular expression with:

\((\X*?)\)

to match everything in parenthesis. If * is repeat 0 or more times and ? is zero or once, it seems extraneous to have both. Is *? equivalent to * or does it have some special meaning with both combined?

Upvotes: 1

Views: 4329

Answers (1)

nneonneo
nneonneo

Reputation: 179717

? after + or * makes that operator non-greedy, that is, it will try to match a minimum number of times instead of a maximum number of times.

For example, matching {hi}{there} with {(.*)} matches the group hi}{there which may be undesirable. Using the non-greedy {(.*?)} gives the matches hi and there as desired.

Upvotes: 8

Related Questions