[英]Ruby: How to remove trailing backslashes from a string?
I have a string like 我有一个字符串
"car\"
which I will be storing in postgres db. 我将存储在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?
有没有办法可以用ruby或postgres做到这一点? When I try to remove it in ruby, it considers the quote after the backslash as an escape character.
当我尝试在ruby中删除它时,它将反斜杠后的引号视为转义字符。
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 >
To remove a trailing backslash: 要删除尾部反斜杠:
"car\\".gsub!(/\\$/, "")
Note that the backslash has to be escaped itself with a backslash. 请注意,反斜杠必须使用反斜杠进行自动转义。
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. 这是条件搜索尾随'\\',并用空字符串替换。
puts '"car\"'.gsub(/\\(")?$/, '\1')
会这样做,但是,总是在en跟随引号的尾随斜线?
See what says the 看看说的是什么
str.dump
operation, and then try to operate on that. 操作,然后尝试操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.