postgresql Ruby:如何从字符串中删除尾部反斜杠?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12897614/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Ruby: How to remove trailing backslashes from a string?
提问by Ari53nN3o
I have a string like
我有一个像
"car\"
which I will be storing in postgres db. I want to remove the backslash from the string before saving. Is there a way I can do that in ruby or in postgres? When I try to remove it in ruby, it considers the quote after the backslash as an escape character.
我将存储在 postgres db 中。我想在保存之前从字符串中删除反斜杠。有没有办法在 ruby 或 postgres 中做到这一点?当我尝试在 ruby 中删除它时,它会将反斜杠后的引号视为转义字符。
回答by Yanhao
See following code:
请参阅以下代码:
1.9.3p125 :022 > s = "cat\"
=> "cat\"
1.9.3p125 :023 > puts s
cat\
=> nil
1.9.3p125 :024 > s.chomp("\")
=> "cat"
1.9.3p125 :025 >
回答by Sébastien Le Callonnec
To remove a trailing backslash:
要删除尾部反斜杠:
"car\".gsub!(/\$/, "")
Note that the backslash has to be escaped itself with a backslash.
请注意,反斜杠必须用反斜杠转义。
回答by the Tin Man
People don't do this much, but Ruby's String class supports:
人们不会这样做,但 Ruby 的 String 类支持:
irb(main):002:0> str = 'car\'
=> "car\"
irb(main):003:0> str[/\$/] = ''
=> ""
irb(main):004:0> str
=> "car"
It's a conditional search for a trailing '\', and replacement with an empty string.
这是对尾随 '\' 的条件搜索,并用空字符串替换。
回答by thebugfinder
puts '"car\"'.gsub(/\(")?$/, '')
that will do it, but, is the trailing slash always at the en followed by a quote?
这样就可以了,但是,结尾的斜杠总是在 en 后面跟一个引号吗?
回答by Adam
See what says the
看看怎么说
str.dump
operation, and then try to operate on that.
操作,然后尝试对其进行操作。