This is a classic example of why the .+
combination can be evil. Use a negated character set instead:
(\$\{(\b[a-zA-Z0-9]+\b)\})(\[([^]]+)\])
^^^
You can try it here.
Compare the behavior of the two expressions:
Match anything greedily. For the second match, the regex matches anything greedily. It will match anything until it reaches the end of the string, and then has to backtrack until it finds a ]
. As soon as it finds a ]
, it stops, hence you end up with [arg1] - ${test2}[arg2]
as a match.
Match anything but a ]. Here the regex is matching anything that is not a ]
, therefore at every step is checks whether the next is a ]
or not. For the second match, you can see that as soon as it finds a ]
, it stops.