How to use "+" metacharacter in Regular Expression.

Whats the use of "+" metacharacter?


The "+" metacharacter otherwise known as quantifier is used to find the number of times a character or a sequence of characters may occur that is at least one or more times.

For example if we have a pattern "lt+" it matches the string that has the letter "l" followed by "t" atleast once or more than once.So it can give match for "lt", "lttttt", "lturt".

PHP Example:

$string = 'laaat';
if (preg_match('/^(l.+t)/', $string))
echo "Pattern match";
echo "Pattern unmatch";
Result :

Pattern match!

In the above example the pattern is '/^(c.+t)/', specifies the string should start with "c" can have any character by ".", end with one or more occurence of "t".

Perl Example:

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

The pattern not found!

In the above example's the pattern "lt+" means the string should start with "l" and should have "t" followed at least once or more times, so the string "lurt" gives a unmatch as "l" is not followed by "t".

Ask Questions

Ask Question