FreeKB - Escape special characters using quotemeta (\Q \E)
Perl - Escape special characters using quotemeta (\Q \E)

There are a number of special characters that are used in regular expressions, such as * . ^ $. If you have a string of data that contains one of the special characters, it can be difficult to manipulate the string of data. This is most often found when attempting to replace the string of data. For example, let's say you've the following string of data.

my $foo = "b*r";


Printing foo will display the wildcard. 



However, let's say you attempt to replace the string of data.

$foo =~ s|b*r|Hello World|;


The result of this will be, which is most certainly not the expected result.

b*Hello World


The solution to this challenge is to escape the special characters.

$foo =~ s|b\*r|Hello World|;


While this is a reasonable solution when working with predicable, static data that will never change (which is extremely rare), this solution will fail when working with dynamic, unpredicable data. To handle this with dynamic, unpredictable data, the quotemeta operator can be used. The quotemeta operator will escape every special character in a string of data. \Q begins quotmeta and \E ends quotemeta. In this example, any special character in the $foo variable will be escaped.

my $foo = "\Qb*r\E";


Printing foo will now show that the wildcard character is escaped. 



Or you can use \Q and \E in a replacement command to escape any special characters in the string being replaced.

$foo =~ s|\Qb*r\E|Hello World|;


Be aware that quotmeta will also escape whitespace and special characters, so you may end up with a lot of escapes when using quotmeta.

A\ quick\ brown\ fox\ jumps\ over\ the\ lazy\ dog\.


Add a Comment

We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.

Please enter 7e2f6 in the box below so that we can be sure you are a human.