我需要一个正则表达式来从Ruby
中的两个单引号之间的字符串中提取引号所以如果我的字符串是str = 'My name is Gaurav's'
正则表达式应该只提取两个单引号之间的引号。
我该怎么做?
答案 0 :(得分:1)
嗯,这很简单:
str.gsub("'", "\\'")
因此字符串Hello, the bike is Mike's
将变为Hello, the bike is Mike\'s
(不包括语法引号)。
答案 1 :(得分:0)
看起来你似乎没有正确定义你的字符串。
如果你想要一个看起来像这样的字符串:
My name is Gaurav's
然后以下列方式之一定义:
str = "My name is Gaurav's"
=> "My name is Gaurav's"
str = %{My name is Gaurav's}
=> "My name is Gaurav's"
str = %q{My name is Gaurav's}
=> "My name is Gaurav's"
str = %Q{My name is Gaurav's}
=> "My name is Gaurav's"
str = 'My name is Gaurav\'s'
=> "My name is Gaurav's"
就个人而言,为简单起见,我使用第一种形式。
如果您正确定义字符串,则无需转义单引号。