Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to escape all special characters in a string (along with single and double quotes)?

Tags:

perl

E.g:

$myVar="this#@#!~`%^&*()[]}{;'".,<>?/\";

I am not able to export this variable and use it as it is in my program.

like image 620
Pradnya Deshmukh Avatar asked Dec 20 '16 06:12

Pradnya Deshmukh


People also ask

How do you escape characters with double quotes?

To cause the C compiler to interpret the double quotation mark as a character, precede the double quotation mark with the C escape character, the backslash (\). The following example illustrates the correct syntax for the query in Table 1: EXEC SQL select col1 from tab1 where col1 = '\"';

How do you escape a single quote from a single quote?

Single quotes tell Integration Engine to take what is enclosed in the single quotes literally. No escaping is used with single quotes. Use a double backslash as the escape character for backslash.

How do you escape characters in a string?

\ is a special character within a string used for escaping. "\" does now work because it is escaping the second " . To get a literal \ you need to escape it using \ .


2 Answers

Use q to store the characters and use the quotemeta to escape the all character

my $myVar=q("this#@#!~`%^&*()[]}{;'".,<>?/\");
$myVar = quotemeta($myVar);

print $myVar;

Or else use regex substitution to escape the all character

my $myVar=q("this#@#!~`%^&*()[]}{;'".,<>?/\");
$myVar =~s/(\W)/\\$1/g;
print $myVar;
like image 75
mkHun Avatar answered Oct 23 '22 13:10

mkHun


This is what quotemeta is for, if I understand your quest

Returns the value of EXPR with all non-"word" characters backslashed. (That is, all characters not matching /[A-Za-z_0-9]/ will be preceded by a backslash in the returned string, regardless of any locale settings.) This is the internal function implementing the \Q escape in double-quoted strings.

Its use is very simple

my $myVar = q(this#@#!~`%^&*()[]}{;'".,<>?/\\);
print "$myVar\n";

my $quoted_var = quotemeta $myVar;
print "$quoted_var\n";

Note that we must manually escape the last backslash, to prevent it from escaping the closing delimiter. Or you can tack on an extra space at the end, and then strip it (by chop).

my $myVar = q(this#@#!~`%^&*()[]}{;'".,<>?/\ );
chop $myVar;

Now transform $myVar like above, using quotemeta.

I take the outside pair of " to merely indicate what you'd like in the variable. But if they are in fact meant to be in the variable then simply put it all inside q(), since then the last character is ". The only problem is a backslash immediately preceding the closing delimiter.

If you need this in a regex context then you use \Q to start and \E to end escaping.

like image 34
zdim Avatar answered Oct 23 '22 11:10

zdim