简体   繁体   中英

Ruby: How to insert three backslashes into a string?

I want to use backticks in ruby for a programm call. The parameter is a String variable containing one or more backticks, ie "&E?@@A`?". The following command yields a new label as its return value:

echo "&E?@@A\`?" | nauty-labelg 2>/dev/null

From a ruby program I can call it as follows and get the correct result:

new_label = `echo "&E?@@A\\\`?" | nauty-labelg 2>/dev/null`

I want to achieve the same using a variable for the label. So I have to insert three slashes into my variable label = "&E?@@A`?"in order to escape the backtick. The following seems to work, though it is not very elegant:

escaped_label = label.gsub(/`/, '\\\`').gsub(/`/, '\\\`').gsub(/`/, '\\\`')

But the new variable cannot be used in the program call:

new_label = `echo "#{escaped_label}" | nauty-labelg 2>/dev/null`

In this case I do not get an answer from nauty-labelg.

So I have to insert three slashes into my variable label = "&E?@@A`?"in order to escape the backtick.

No, you only need to add one backslash for the output. To escape the ` special bash character. The other other two are only for representation proposes, otherwise it isn't valid Ruby code.

new_label = `echo "&E?@@A\\\`?" | nauty-labelg 2>/dev/null`

The first backslash will escape the second one (outputting one single backslash). The third backslash escapes the ` character (outputting one single ` ).

You should only add backslashes before characters that have a special meaning within double quoted bash context. These special characters are: $ , ` , \\ and \\n . Those can be escaped with the following code:

def escape_bash_string(string)
  string.gsub(/([$`"\\\n])/, '\\\\\1')
end

For label = "&E?@@A`?" only the ` should be escaped.

escaped_string = escape_bash_string("&E?@@A\`?")
puts escaped_string
# &E?@@A\`?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM