Search code examples
regexstringstring-matching

What is the difference of regex Quantifier: .* and .*?


For regular expression match ^(?s).*?HOLIDAY.*?INN.*?EXPRESS.*?$ and ^(?s).*HOLIDAY.*INN.*EXPRESS.*$ what is the benefit of using .*? instead of .* ?

In other words what is the difference of regex quantifier: .* and .*?


Solution

  • * is a greedy quantifier, which means that it will match as many letters possible. *? is a non greedy quantifier, it will match the smallest number of letters possible.

    To understand the difference in this case, let's look at the following fragment or the regular expression: HOLIDAY.*?INN. In this one, .*? will match with the text between the string HOLIDAY and the first INN that it will encounter after that. Without the ? it is possible that it would find an INN that is much further far away.