Mega Code Archive

 
Categories / Perl / Regular Expression
 

Greedy searches

greedy means that each pattern will try to match as much as it can.  The pattern /a.*a/ matches as many characters as possible between the first a and the last a.  If your text string is ababacdea, /a.*a/ will match the whole string. You can control the greediness using a question mark.  The question mark matches a minimum number of times.  The following table shows how to minimize the greediness.  Syntax         Means *?             Match zero or more times, minimal number of times +?             Match one or more times, minimal number of times ??             Match zero or one time, minimal number of times {num}?         Match exactly num times, minimal number of times {num,}?        Match at least num times, minimal number of times {num,max}?     Match at least num but not more than max times, minimal number of times