Word metacharacter "w" in Regular Expression

How is word metacharacter "w" used in regex?

Explanation

The "w" metacharacter is used to match any word character including underscore "_" in regular expression.The word character's are "[a-z][A-Z][0-9]".

PHP Example:


<?php
$emp = "&nart";
if (preg_match("/w/", $emp, $matches))
{echo "Pattern matches!";
print "<br>";
echo $matches[0];}
else
{echo "Pattern not matched!";}
?>
Result :

Pattern matches!
a

In the above example of regex, "a" is the only word character, so its matched.

Perl Example:


#! C:programfilesperlbinperl
print "content-type: text/htmlnn";
$name= "n*r>f";
if ($name =~ m/w/)
{print "It's matched!";}
else
{print "It's not matched!";}
Result :

It's not matched!

In the above example for word metacharacter in regex, the pattern "/w/" is unmatched as the string does not have any word characters.

Ask Questions

Ask Question