Tuesday, June 20, 2006

Regular Expressions : Dealing with special characters like asterisk

This post is for beginners of perl/regular expressions who find it hard to deal with special characters like asterisks if they appear in patterns. For instance, here is a pattern that contains an asterisk
4*3
If you want to replace or remove the asterisk, you will have to escape it with a back-slash ('\') in a regular expression. Following is a sample code.

$x = "4*3";
print "$x\n";

## following line removes the special character asterisk from the scalar $x
## note that the asterisk is 'escaped' by using a back-slash
$x =~ s/\*//;

print "$x\n";


Output

4*3

43

Use of a back-slash ('\') for escaping special characters is common where regular expressions are used. It's also used for escaping spaces in directory-names on shell prompt.

Some examples

character : escaping it
\ : \\
* : \*
+ : \+
/ : \/

No comments: