How can I write a regex which matches non greedy?

Pointer Null picture Pointer Null · Aug 10, 2012 · Viewed 375.7k times · Source

I need help about regular expression matching with non-greedy option.

The match pattern is:

<img\s.*>

The text to match is:

<html>
<img src="test">
abc
<img
  src="a" src='a' a=b>
</html>

I test on http://regexpal.com

This expression matches all text from <img to last >. I need it to match with the first encountered > after the initial <img, so here I'd need to get two matches instead of the one that I get.

I tried all combinations of non-greedy ?, with no success.

Answer

Pavan Manjunath picture Pavan Manjunath · Aug 10, 2012

The non-greedy ? works perfectly fine. It's just that you need to select dot matches all option in the regex engines (regexpal, the engine you used, also has this option) you are testing with. This is because, regex engines generally don't match line breaks when you use .. You need to tell them explicitly that you want to match line-breaks too with .

For example,

<img\s.*?>

works fine!

Check the results here.

Also, read about how dot behaves in various regex flavours.