Chr*_*ton 35 ruby regex string
我想从一个字符串中删除Ruby中的前导和尾随引号.引号字符将出现0或1次.例如,以下所有内容都应转换为foo,bar:
"foo,bar""foo,barfoo,bar"foo,barChr*_*ton 37
我可以使用gsub搜索前导或尾随引用并用空字符串替换它:
s = "\"foo,bar\""
s.gsub!(/^\"|\"?$/, '')
Run Code Online (Sandbox Code Playgroud)
如下面的评论所示,更好的解决方案是:
s.gsub!(/\A"|"\Z/, '')
Run Code Online (Sandbox Code Playgroud)
grd*_*dev 34
你也可以使用这个chomp函数,但不幸的是它只能在字符串的末尾起作用,假设有一个反向的chomp,你可以:
'"foo,bar"'.rchomp('"').chomp('"')
Run Code Online (Sandbox Code Playgroud)
实施rchomp很简单:
class String
def rchomp(sep = $/)
self.start_with?(sep) ? self[sep.size..-1] : self
end
end
Run Code Online (Sandbox Code Playgroud)
请注意,您也可以使用效率稍低的版本进行内联:
'"foo,bar"'.chomp('"').reverse.chomp('"').reverse
Run Code Online (Sandbox Code Playgroud)
编辑:既然红宝石2.5,rchomp(x)是的名义下获得delete_prefix,并且chomp(x)可以作为delete_suffix的,这意味着你可以使用
'"foo,bar"'.delete_prefix('"').delete_suffix('"')
Run Code Online (Sandbox Code Playgroud)
the*_*Man 22
像往常一样,每个人都首先从工具箱中获取正则表达式.:-)
作为替代方案,我建议调查.tr('"', '')(AKA"翻译"),在这个用途中,它实际上是剥离报价.
另一种方法是
remove_quotations('"foo,bar"')
def remove_quotations(str)
if str.start_with?('"')
str = str.slice(1..-1)
end
if str.end_with?('"')
str = str.slice(0..-2)
end
end
Run Code Online (Sandbox Code Playgroud)
没有RegExps和start_with?/ end_with?非常好读.
| 归档时间: |
|
| 查看次数: |
50019 次 |
| 最近记录: |