Regular Expression Meta-character Brace "[]"

What is regular expression meta-character Brace "[]"?

Explanation

In Regular Expression, the meta-character Brace "[]" is used to match the range of characters like [a-z] or characters like [abc] enclosed within it, but when used with "^" that is like [^abc] the pattern matches character's other than "abc".

Following are some basic brace expressions that can be used for alphabets and numbers.
Expression Description
[0-9] Used to match number from 0 to 9
[a-z] Used to match lowercase alphabets from a to z
[A-Z] Used to match uppercase alphabets from A to Z
[a-Z] Used to match alphabets through lowercase a to uppercase Z

Not just the above expressions, it can also be used for our convenience like [a-d] for lowercase alphabets from a to d,[0-3] specifies numbers from 0 to 3.If the pattern is specifed like "^[a-Z]" means that the string should start with alphabets either upper or lower case, but if the same pattern is specified like "[^a-z]" matches any number not an alphabet either upper or lower case.

PHP Example:


<?php
$name = "bit";
if (preg_match("/b[aeiu]t/", $name))
{echo "Regex Pattern matches!";}
else
{echo "Regex Pattern not matched!";}
?>
Result :

Pattern matches!

In the above example "aeiu" is similar to "a|e|i|u", so the possible matches would be "bat","bet","bit", "but".

One can also use advanced patterns like "([A-Z]{2}|[0-9]{5})" matches 2 letters and 5 numbers, so a string can be matched only if it is like "AD78564".

Perl Example:


#! C:programfilesperlbinperl
print "content-type: text/htmlnn";
if ("laa235452er" =~ m/([A-Z]{2}|[0-9]{5})/)
{print "The pattern matched.!n";}
else
{print "The pattern not found!n";}
Result :

The pattern matched.!

In the above example's the pattern "([A-Z]{2}|[0-9]{5})" matches a string if it has "5" numbers and "2" letters.


Ask Questions

Ask Question