Regular Expression Meta-character Caret "^"

What is Regular Expression meta-character Caret "^"?

Explanation

In Regular Expression, the "^" meta-character is used to match the characters from the begining of a string.

For example if we use "^The" then it tries to match the begining of the string for "The".

PHP Example:


<?php
$string = "This is a church";
if (preg_match("/^This/", $string))
{
echo "Regex Pattern matches at the begining!";
}
else
{
echo "Regex Pattern not matched!";
}
?>
Result :

Regex Pattern matches at the begining!

In the above example the string is checked for the pattern "^This" at the begining of the string "$string" , so it is matched.

Perl Example:


#! C:programfilesperlbinperl
print "content-type: text/htmlnn";
if ("This is a (templateVar)" =~ m/^is/)
{ print "The pattern found at the begining of string.!n"; }
else
{ print "The pattern not found!n";}
Result :

The pattern not found!

In the above example the string is matched for the pattern "/^is/", since it is not matched at the begining of the string its unmatched.


Ask Questions

Ask Question