在Ruby中如何避免单引号? [英] How do I escape a single quote in Ruby?
问题描述
JSON中的某些内容包含单个字符串引用,所以我想确保任何单引号在传递到脚本之前被转义。
我已经尝试了以下内容:
> irb
> 1.9.3p194:001> x =这是一个真棒字符串
> => 这是一个真棒字符串
> 1.9.3p194:002> x.sub(',\)
> => 这是一个真棒字符串
> 1.9.3p194:003> x.sub(',\\)
> => 这是一个令人敬畏的字符串真棒字符串
但似乎无法获得正确的语法。 / p>
原因 sub(',\)
不工作是因为\
与相同。在双引号内,转义单引号是可选的。
原因 sub(',\\\ / code>不起作用是因为
的\\
扩展为反斜杠后跟单引号。在 sub
或 gsub
参数中,后面跟一些字符的反斜杠具有与相应的全局变量相当的特殊意义。特别是在这种情况下,全局变量 $'
在最后一个匹配点之后保存子字符串。在 sub
或中的
gsub \\
gsub sub
:
gsub('){\ \'}
I am passing some JSON to a server via a script (not mine) that accepts the JSON as a string.
Some of the content of the JSON contains single quotes so I want to ensure that any single quotes are escaped before being passed to the script.
I have tried the following:
> irb
> 1.9.3p194 :001 > x = "that's an awesome string"
> => "that's an awesome string"
> 1.9.3p194 :002 > x.sub("'", "\'")
> => "that's an awesome string"
> 1.9.3p194 :003 > x.sub("'", "\\'")
> => "thats an awesome strings an awesome string"
but can't seem to get the syntax right.
The reason sub("'", "\'")
does not work is because "\'"
is the same as "'"
. Within double quotes, escaping of a single quote is optional.
The reason sub("'", "\\'")
does not work is because "\\'"
expands to a backslash followed by a single quote. Within sub
or gsub
argument, a backslash followed by some characters have special meaning comparable to the corresponding global variable. Particularly in this case, the global variable $'
holds the substring after the last matching point. Your "\\'"
within sub
or gsub
argument position refers to a similar thing. In order to avoid this special convention, you should put the replacement string in a block instead of an argument, and since you want to match not just one, you should use gsub
instead of sub
:
gsub("'"){"\\'"}
这篇关于在Ruby中如何避免单引号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!