Quantifiers in Regular Expression

What are Quantifiers?

Explanation

Quantifiers are used to specify the number of times a certain pattern can be matched consecutively. A quantifier is specified by putting the range expression inside a pair of curly brackets.A maximal or greedy search tries to match as many characters possible, still returning a true value. So if we were looking for 1 to 5 a's in a row and had a string with 3 a's in a row we would match the 3 a's. If it was a minimal or nongreedy search only the first a would be matched.

The following are some of the quantifiers used in regular expression.
Greedy No Greedy Allowed numbers for a match
? ?? 0 or 1 time
+ +? 1 or more times
* *? 0 or more times
{m} {m}? match exactly m times
{m,} {m,}? match m or more times
{m,n} {m,n}? match at least m times and at most n times

Example :


#! C:programfilesperlbinperl
print "content-type: text/htmlnn";
$str= "exagerate";
if ($str =~ /e(.*)e/)
{
print "The value using a greedy or Maximum Match is::$1";
}
print "<br>";
if ($str =~ /e(.*?)e/)
{
print "The value using a non greedy or Minimum Match::$1";
}
Result :

The value using a greedy or Maximum Match is::xagerat
The value using a non greedy or Minimum Match::xag

In the above example the first the string "exagerate" is matched in greedy or maximum method ,so string after the first occurence of "e" to last occurence of is displayed. In the second example only the matches the string between the first and second occurence of the letter "e" is displayed as it uses the non greedy method.

Ask Questions

Ask Question