How do I remove \\"
from a string?
Example:
'"\"asdasd"\"'.gsub('\"', '') # => "\"asdasd\""
Why is \\"
not removed?
It is removed. The \\"
in the output is not a backslash followed by a double quote, it's just a double quote character that's escaped because inspect
prints strings in double quotes. If you try to print the string, it'll come out as:
"asdasd"
To expand on this a bit: '"\\"asdasd"\\"'
(which can also be written using double quotes as "\\"\\\\\\"asdasd\\"\\\\\\""
) is a string that contains a double quote, followed by a backslash, followed by a double quote, followed by asdasd, followed by a double quote, followed by a backslash, followed by a double quote.
Your call to gsub
removes the two occurrences of backslashes followed by double quotes. The result is "\\"asdasd\\""
, which could also be written as '"asdasd"'
and is a string containing a double quote, followed by asdasd, followed by a double quote. So the backslash-double quotes were removed, but the simple double quotes weren't. I assume that's the intended behavior.
In ruby special symbol is preceding by backslash when convert into string. ie "\\"
to the \\"\\\\\\"
Check this you will understand
'"\"asdasd"\"' # => "\"\\\"asdasd\"\\\""
'"\"asdasd"\"'.gsub("\\", '') # => "\"\"asdasd\"\""
'"\"asdasd"\"'.gsub("\\", '').gsub("\"", '') # => "asdasd"
How is this ?
str = '"\"asdasd"\"'
p str[/\w+/] # => "asdasd"
It did remove them. Here's what the string looks like when inspect
ed before the change:
'"\"asdasd"\"' # => "\"\\\"asdasd\"\\\""
And here's after:
'"\"asdasd"\"'.gsub('\"','') # => "\"asdasd\""
So it previously had some backslash-quotation mark sequences in it. Now it just has quotation marks.
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.