使用Ruby正则表达式将常规双引号转义为“" [英] Escaping '“' with regular double quotes using Ruby regex

查看:128
本文介绍了使用Ruby正则表达式将常规双引号转义为“"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的文字中有这些花哨的双引号:",我想使用Ruby gsub和regex将它们替换为常规的双引号.这是一个例子,到目前为止,我有什么:

I have text that has these fancy double quotes: '"' and I would like to replace them with regular double quotes using Ruby gsub and regex. Here's an example and what I have so far:

sentence = 'This is a quote, "Hey guys!"'  

I couldn't figure out how to escape double quotes so I tried using 34.chr:
sentence.gsub(""",34.chr).  This gets me close but leaves a back slash in front of the double quote:

sentence.gsub(""",34.chr) => 'This is a quote, \"Hey guys!"' 

推荐答案

由于反斜杠打印出语句结果的方式,反斜杠仅显示在irb中.如果您将gsub ed字符串传递给另一个方法,例如puts,则在转义转义序列后,您会看到真实"表示形式.

The backslashes are only showing up in irb due to the way it prints out the result of a statement. If you instead pass the gsubed string to another method such as puts, you'll see the "real" representation after escape sequences are translated.

1.9.0 > sentence = 'This is a quote, "Hey guys!"'  
 => "This is a quote, \342\200\234Hey guys!\342\200\235" 
1.9.0 > sentence.gsub('"', "'")
 => "This is a quote, 'Hey guys!\342\200\235" 
1.9.0 > puts sentence.gsub('"', "'")  
This is a quote, 'Hey guys!"
 => nil

还要注意,在输出puts之后,我们看到=> nil表示puts 的调用返回了nil.

Note also that after the output of puts, we see => nil indicating that the call to puts returned nil.

您可能已经注意到,有趣的引号仍位于puts输出的末尾:这是因为引号是两个不同的转义序列,我们只命名了一个.但是我们可以使用gsub中的正则表达式来解决:

You probably noticed that the funny quote is still on the end of the output to puts: this is because the quotes are two different escape sequences, and we only named one. But we can take care of that with a regex in gsub:

1.9.0 > puts sentence.gsub(/("|")/, 34.chr)
This is a quote, "Hey guys!"
 => nil

此外,在许多情况下,您可以在Ruby字符串中交换单引号和双引号-双引号执行扩展,而单引号则不行.您可以通过以下几种方法来获取仅包含双引号的字符串:

Also, in many cases you can swap single quotes and double quotes in Ruby strings -- double quotes perform expansion while single quotes do not. Here are a couple ways you can get a string containing just a double quote:

1.9.0 > '"' == 34.chr
 => true 
1.9.0 > %q{"} == 34.chr
 => true 
1.9.0 > "\"" == 34.chr
 => true 

这篇关于使用Ruby正则表达式将常规双引号转义为“"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆