删除带有正则表达式的字符串中的\

时间:2015-03-24 21:12:10

标签: ruby regex

我有一个示例字符串,如下所示......

 "{:@text=>"\"Question 12\" must be answered when  \"question 10 / Question 11 (or Question 9)\" answered"}"

我只想提取文字:

当问题10 /问题11(或问题9)回答“

时,必须回答问题12

我试过用这个:

@object.scan(/@text=>"(.*?)"/).flatten.map{ |msg| msg.gsub(/(\.|\s+)/, '').strip }

然而,只返回\

我还能尝试什么?

2 个答案:

答案 0 :(得分:2)

这不是有效的字符串。你有字符串:

 "#{:@text=>"

接下来是:

 \"Question 12\" must be answered when  \"question 10 / Question 11 (or Question 9)\" answered"}"

使用单引号:

str = '{:@text=>"\"Question 12\" must be answered when  \"question 10 / Question 11 (or Question 9)\" answered"}'

然后

puts str.gsub(/\{:@text=>|\"|\\|\}/,'')
  #=> Question 12 must be answered when  question 10 / Question 11 (or Question 9) answered

答案 1 :(得分:0)

您可以尝试使用/\/|\w+/

[13] pry(main)> str
=> "{:@text=>\"\\\"Question 12\\\" must be answered when  \\\"question 10 / Question 11 (or Question 9)\\\" answered\"}"
[14] pry(main)> str.scan(/\/|\w+/).join(" ")
=> "text Question 12 must be answered when question 10 / Question 11 or Question 9 answered"