Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differences between (.*) and (.*?) [duplicate]

Tags:

regex

php

Possible Duplicate:
what does lazy and greedy means in regexp?

I know that in Regex the question mark after *, + or ? means ungreedy but if I want to match any character, what is the difference between using (.*) or (.*?) ?

Thanks.

EDIT: In my case I want to check a URL. What are the differences between

http://site\.net/(.*?)\.html

and

http://site\.net/(.*)\.html

?

like image 906
mcont Avatar asked Dec 03 '25 09:12

mcont


1 Answers

.* is greedy, meaning that it will ignore the next delimiter of your regex until it itself is not fulfilled, unless the regex following .* is against the end of the target string.

.*? is ungreedy, meaning that it will proceed to the next delimiter of your regex, if the next is fulfilled. It will continue onto the next delimiter even if itself is still applicable.

Example:

/(.*) dog/ will match "I think your dog bit my dog" and group 1 will be "I think your dog bit my".

/(.*?) dog/ will match "I think your dog bit my dog" and group 1 will be "I think your".

like image 72
FThompson Avatar answered Dec 06 '25 00:12

FThompson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!