'What is the difference between .* and .*? in a regular expression?

I am trying to learn about regular exprssoins. While investigating the difference between re.match and re.search I saw a (disputed) claim that re.match('(.*?)word(.*?)',string) was faster than re.search("word",string) I do not see the difference between .*? and .* nor do I see a need for the trailing (.*?) .



Solution 1:[1]

To understand any regex, the first place you go should always be https://regex101.com/. In this case, here's what it says is the only difference between the two:

* matches the previous token between zero and unlimited times, as many times as possible, giving back as needed (greedy)

*? matches the previous token between zero and unlimited times, as few times as possible, expanding as needed (lazy)

And from there, you can then enter in example text in order to test out the expression in realtime and see what the practical difference is.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Random Davis