(.*) instead of (.*?)

Suppose we have this html content, and we are willing to get Content1, Content2,.. with regular expression.

<li>Content1</li>
<li>Content2</li>
<li>Content3</li>
<li>Content4</li>

If I use the line below

preg_match_all('/<li>(.*)<\/li>/', $text, $result);

i will get an array with a single row containing:

Content1</li>
<li>Content2</li>
<li>Content3</li>
<li>Content4

And by using this code:

preg_match_all('/<li>(.*?)<\/li>/', $text, $result);

i will get an array with 4 row containing Content1, Content2, ...

Why (.*) is not working since it means match any character zero or more times

Answers


* matches in a greedy fashion, *? matches in a non-greedy fashion.

What this means is that .* will match as many characters as possible, including all intermediate </li><li> pairs, stopping only at the last occurrence of </li>. On the other hand, .*? will match as few characters as possible, stopping at the first occurrence of </li>.


Because .* itself is greedy and eats up as much as it can (i.e. up to the last </li>) while still allowing the pattern to match. .*? on the other hand is not greedy and eats up as little as possible (stopping at first </li>).


See this article's section about greedyness of regular expressions.


Need Your Help

TIdMBCSEncoding.Create('ASCII') returns with MaxCharSize = 0 on Linux

linux delphi indy freepascal iconv

My environment is Ubuntu 12.04 Linux on i386. I can see that only UTF-8 locales are installed (in /var/lib/locales/supported.d/local):

Xcode 7 and Swift 2.0 Refractoring possible?

macos swift swift2 xcode7 xcode7-beta4

I'm planning to upgrade my code to swift 2.0 and to use Xcode 7 in the near future. At the moment my app is still dependen on some frameworks that do not work with Swift2.0 yet.