How to use "{}" metacharacter in Regular Expression.

Whats the use of "{}" metacharacter?

Explanation

The "{}" braces metacharacter otherwise known as quantifiers is used to specify the range for matching the patterns.
Metacharacter Description
{n} Match n times
{n,} Match n or more times
{m,n} Match atleast m times,and utmost n times

The pattern "o{3}l" will match strings like "loool", "oool", "llloool" as all the strings have only three o's followed by an "l".If the pattern "o{3,}l" it will match the strings like "ooooooool", "looooool" etc. Exactly a range can be given using the pattern "o{2,4}l" will match the strings like "lool","loool","looool" etc.

To match a sequence of characters, try a pattern "o(lu)*" where it matches a "o" followed by zero or more occurences of the pattern "lu", the matches can be "o","olu", "olulu" etc. Same pattern can also be given within a range like "o(lu){1,2}" possible matches would be "o","olu","olulu" only.

PHP Example:


<?php
$name = "live1";
if (preg_match("/^.{2,4}$/", $name))
{ echo "Pattern matches!";}
else
{ echo "Pattern not matched!";}
?>
Result :

Pattern not matched!

In the above example the pattern "/^.{2,4}$/" this matches any string with 2 to 4 characters, since "live1" has five character's it is not matched, but if changed to "live" it can be a matched.

Perl Example:


#! C:programfilesperlbinperl
print "content-type: text/htmlnn";
if ("oooool" =~ m/o{2,4}l/)
{print "The pattern matched.!n";}
else
{ print "The pattern not matched!n"; }
Result :

The pattern matched!

In the above example's the pattern "o{2,4}l" means the string should have atleat 2 to 4 "o"s followed by "l", since that string "oooool" has 5 o's, followed by a "l", the pattern is matched because the exceeding range is negelected after the match.

Ask Questions

Ask Question