alnum Character Class in Regular expression

What is [[:alnum:]] Character Class in regex?

Explanation

The [[:alnum:]] character class represents alphabetic and numeric characters, and it is same as using [a-zA-Z0-9] in regular expression.

PHP Example:


<?php
$org = 'AAA**&18';
$det = ereg_replace("[[:alnum:]]","@",$org);
echo $det;
?>
Result :

@@@**&@@

In the above regex example the character class "[[:alnum:]]" is used along with the metacharacter "^",which specifies to match the begining of the string, since the string has the number "1" in the beginning its matched.

Perl Example:


#! C:programfilesperlbinperl
print "content-type: text/htmlnn";
$str = "wew436*3631";
if ( $str =~ /[^[:alnum:]]/ )
{print "Character other than alphanumeric!";}
else
{print "Only alphanumeric characters!";}
Result :

Character other than alphanumeric!

In the above example the metacharacter "^" refers the begining of the string, but here its used like "/[^[:alnum:]]/" which means "NOT" a alphanumeric character. Since the string has a "*" it matches as it not a alphanumeric character.

Ask Questions

Ask Question