How to use "*" Quantifier in Regular Expression.

Quantifier "*" in Regular Expression?

Explanation

The "*" quantifier is used to know the number of times a character or a sequence preceding "*" may occur at least zero or more times.It just matches any number of occurence or even if does'nt occur.

For example if we have a pattern "lt*" it matches the string that has the letter "l" followed by zero or more number of "t" as it is the preceding character to the quantifier "*". So the string matched would be "l","ltt","later" etc.

PHP Example:


<?php
$name = "bcd";
if (preg_match("/a(bcd)*/", $name))
{echo "Pattern matches!";}
else
{echo "Pattern not matched!";}
?>
Result :

Pattern not matched!

In the above example the possible matches are "a", "abcd", "abcdbcd" etc. Here "bcd" is grouped using a "()" to match zero or more times.

Perl Example:


#! C:programfilesperlbinperl
print "content-type: text/htmlnn";
if ("laaer" =~ m/lt*/)
{
print "The pattern matched.!n";
}
else
{
print "The pattern not found!n";
}
Result :

The pattern matched.!

In the above example's the pattern "lt*" means the string should start with "l" with a following "t" or even can be without a "t" ie., so the string "laaer" is matched.

Ask Questions

Ask Question