views:

41

answers:

3

I want to match expressions that begin with "${" and end with "}" in the expression ${foo} and ${bar}.

The regex .*\$\{.+\}.* matches the entire expression, of course.

My understanding was that changing to the reluctant quantifier would solve the problem, but I find that .*\$\{.+?\}.* also matches the entire expression.

What am I missing?

+2  A: 

I would start by removing the .* at the start and the end of the expression - it is probably this that is matching everything. If you try this does it work?

\$\{.+\}
1800 INFORMATION
rememebr that potenetially .* matches the empty string, and you can find an empty string anywhere :) (this entirely depends no the regex engine in use)
Pod
+3  A: 

As well as the suggestion by 1800 INFORMATION i would change the dot to something else:

\$\{[^\}]+\}

As the + will match as much as it can even a } if you have two occurances of ${} in the string.

Question Mark
A: 

The "+" quantifier is greedy, so it matches as much as it can, while +?, matches just enough.

For example, for "${foo} something ${bar}"

".+" --> match = "${foo} something ${bar}" ".+?" --> match = "${foo}" and "${bar}". You will have to iterate to get all the matches.

http://www.regular-expressions.info/repeat.html

dcruz
That's what I understood before. My confusion was why ".+?" wasn't matching as little as possible.
FarmBoy