Regexp non greedy and greedy pattern
Lets get into the matter right away, take the regular expression below as an example. It will try to match any character at least once.
The above pattern is greedy because it tries to match till the end of the input. It won’t stop at the first match. For example suppose we have some html content as shown below.
<h>title</h><p>Content goes here …</p>
Say we are parsing the above text with the patten to extract the tags with the regular expression /<.+>/. We get the entire sentence as match because the matching doesn’t end at the first </h>, it continues till the end and matches with the last </p>.
So how do we make it non-greedy ?
By adding “?” the pattern becomes non greedy ie. the matching ends when the first time match happens. Now if you try to match the above example with non greedy patters /<.+?>/. The matching will happen at each tag enclosed in <>.