我有一个像这样的字符串
a="[\"6000208900\",\"600020890225\",\"600900231930\"]"
#expected result [6000208900,600020890225,600900231930]
我正在尝试从字符串中删除反斜杠。
a.gsub!(/^\"|\"?$/, '')
答案 0 :(得分:5)
Inside the double quoted string(""
),另一个双引号必须由\
转义。你不能删除它。
使用puts
,您可以看到它不存在。
a = "[\"6000208902912790\"]"
puts a # => ["6000208902912790"]
或使用JSON
irb(main):001:0> require 'json'
=> true
irb(main):002:0> a = "[\"6000208902912790\"]"
=> "[\"6000208902912790\"]"
irb(main):003:0> b = JSON.parse a
=> ["6000208902912790"]
irb(main):004:0> b
=> ["6000208902912790"]
irb(main):005:0> b.to_s
=> "[\"6000208902912790\"]"
更新(根据OP的最后一次修改)
irb(main):002:0> a = "[\"6000208900\",\"600020890225\",\"600900231930\"]"
=> "[\"6000208900\",\"600020890225\",\"600900231930\"]"
irb(main):006:0> a.scan(/\d+/).map(&:to_i)
=> [6000208900, 600020890225, 600900231930]
irb(main):007:0>
答案 1 :(得分:1)
代码a.gsub!(/^\"|\"?$/, '')
无法删除双引号字符,因为它们不在字符串的开头和结尾。要得到你想要的东西,试试这个:
a.gsub(/((?<=^\[)")|("(?=\]$))/, '')
答案 2 :(得分:0)
试试这个:
=> a = "[\"6000208902912790\"]"
=> a.chars.select{ |x| x =~ %r|\d| }.join
=> "6000208902912790"
=> [a.chars.select { |x| x =~ %r|\d| }.join]
=> ["6000208902912790"] # <= array with string
=> [a.chars.select { |x| x =~ %r|\d| }.join].to_s
=> "[\"6000208902912790\"]" # <= come back :)
答案 3 :(得分:0)
a="["6000208902912790"]" will return `unexpected tINTEGER`error;
所以a="[\"6000208902912790\"]"
与\
字符一起用于双引号。
作为解决方案,您应该尝试删除可以解决问题的双引号。
这样做
a.gsub!(/"/, '')