如何在Ruby中从字符串中去掉引导和跟踪引用?

时间:2021-06-26 20:23:28

I want to strip leading and trailing quotes, in Ruby, from a string. The quote character will occur 0 or 1 time. For example, all of the following should be converted to foo,bar:

我想从一个字符串中去掉前面和后面的引号。引号字符将出现0或1次。例如,以下所有内容都应该转换为foo,bar:

  • "foo,bar"
  • “foo,酒吧”
  • "foo,bar
  • “foo,酒吧
  • foo,bar"
  • foo,酒吧”
  • foo,bar
  • foo,酒吧

9 个解决方案

#1


28  

You could also use the chomp function, but it unfortunately only works in the end of the string, assuming there was a reverse chomp, you could:

你也可以使用chomp函数,但不幸的是它只在弦的末端起作用,假设有一个反向的chomp,你可以:

'"foo,bar"'.rchomp('"').chomp('"')

Implementing rchomp is straightforward:

实现rchomp很直观:

class String
  def rchomp(sep = $/)
    self.start_with?(sep) ? self[sep.size..-1] : self
  end
end

Note that you could also do it inline, with the slightly less efficient version:

请注意,您也可以使用效率稍低的版本进行内联操作:

'"foo,bar"'.chomp('"').reverse.chomp('"').reverse

#2


35  

I can use gsub to search for the leading or trailing quote and replace it with an empty string:

我可以使用gsub搜索前引或后引,并用空字符串替换:

s = "\"foo,bar\""
s.gsub!(/^\"|\"?$/, '')

As suggested by comments below, a better solution is:

如下面的评论所示,更好的解决办法是:

s.gsub!(/\A"|"\Z/, '')

#3


22  

As usual everyone grabs regex from the toolbox first. :-)

和往常一样,每个人首先从工具箱中获取regex。:-)

As an alternate I'll recommend looking into .tr('"', '') (AKA "translate") which, in this use, is really stripping the quotes.

作为替代,我建议研究。tr(' '' ', ')(也称为"翻译"),在这里,它实际上是去掉了引号。

#4


8  

Another approach would be

另一种方法是

remove_quotations('"foo,bar"')

def remove_quotations(str)
  if str.starts_with?('"')
    str = str.slice(1..-1)
  end
  if str.ends_with?('"')
    str = str.slice(0..-2)
  end
end 

It is without regexps and starts_with?/end_with? are nicely readable.

它没有regexp和starts_with?/end_with?可读得很漂亮。

#5


3  

It frustrates me that strip only works on whitespace. I need to strip all kinds of characters! Here's a String extension that will fix that:

让我沮丧的是,条带只能在空格上工作。我需要去除所有的角色!这里有一个字符串扩展,它将解决这个问题:

class String
  def trim sep=/\s/
    sep_source = sep.is_a?(Regexp) ? sep.source : Regexp.escape(sep)
    pattern = Regexp.new("\\A(#{sep_source})*(.*?)(#{sep_source})*\\z")
    self[pattern, 2]
  end
end

Output

输出

'"foo,bar"'.trim '"'         # => "foo,bar"
'"foo,bar'.trim '"'          # => "foo,bar"
'foo,bar"'.trim '"'          # => "foo,bar"
'foo,bar'.trim '"'           # => "foo,bar"

'  foo,bar'.trim             # => "foo,bar"
'afoo,bare'.trim /[aeiou]/   # => "foo,bar"

#6


1  

I wanted the same but for slashes in url path, which can be /test/test/test/ (so that it has the stripping characters in the middle) and eventually came up with something like this to avoid regexps:

我想要的是相同的,但是对于斜杠的url路径,它可以是/测试/测试/测试/(这样它就有了中间的剥离字符),最终产生了这样的东西来避免regexp:

'/test/test/test/'.split('/').reject(|i| i.empty?).join('/')

Which in this case translates obviously to:

在这种情况下,很明显的意思是:

 '"foo,bar"'.split('"').select{|i| i != ""}.join('"')

or

'"foo,bar"'.split('"').reject{|i| i.empty?}.join('"')

#7


0  

Regexs can be pretty heavy and lead to some funky errors. If you are not dealing with massive strings and the data is pretty uniform you can use a simpler approach.

Regexs可能非常重,会导致一些奇怪的错误。如果你没有处理大量的字符串并且数据是统一的,你可以使用一种更简单的方法。

If you know the strings have starting and leading quotes you can splice the entire string:

如果你知道字符串有起始和前引语,你可以将整个字符串拼接在一起:

string  = "'This has quotes!'"
trimmed = string[1..-2] 
puts trimmed # "This has quotes!"

This can also be turned into a simple function:

这也可以变成一个简单的函数:

# In this case, 34 is \" and 39 is ', you can add other codes etc. 
def trim_chars(string, char_codes=[34, 39])
    if char_codes.include?(string[0]) && char_codes.include?(string[-1])
        string[1..-2]
    else
        string
    end
end

#8


-1  

Assuming that quotes can only appear at the beginning or end, you could just remove all quotes, without any custom method:

假设引号只能出现在开头或结尾,你可以删除所有的引号,不需要任何自定义方法:

'"foo,bar"'.delete('"')

#9


-1  

You can strip non-optional quotes with scan:

你可以带扫描的非可选引号:

'"foo"bar"'.scan(/"(.*)"/)[0][0]
# => "foo\"bar"

#1


28  

You could also use the chomp function, but it unfortunately only works in the end of the string, assuming there was a reverse chomp, you could:

你也可以使用chomp函数,但不幸的是它只在弦的末端起作用,假设有一个反向的chomp,你可以:

'"foo,bar"'.rchomp('"').chomp('"')

Implementing rchomp is straightforward:

实现rchomp很直观:

class String
  def rchomp(sep = $/)
    self.start_with?(sep) ? self[sep.size..-1] : self
  end
end

Note that you could also do it inline, with the slightly less efficient version:

请注意,您也可以使用效率稍低的版本进行内联操作:

'"foo,bar"'.chomp('"').reverse.chomp('"').reverse

#2


35  

I can use gsub to search for the leading or trailing quote and replace it with an empty string:

我可以使用gsub搜索前引或后引,并用空字符串替换:

s = "\"foo,bar\""
s.gsub!(/^\"|\"?$/, '')

As suggested by comments below, a better solution is:

如下面的评论所示,更好的解决办法是:

s.gsub!(/\A"|"\Z/, '')

#3


22  

As usual everyone grabs regex from the toolbox first. :-)

和往常一样,每个人首先从工具箱中获取regex。:-)

As an alternate I'll recommend looking into .tr('"', '') (AKA "translate") which, in this use, is really stripping the quotes.

作为替代,我建议研究。tr(' '' ', ')(也称为"翻译"),在这里,它实际上是去掉了引号。

#4


8  

Another approach would be

另一种方法是

remove_quotations('"foo,bar"')

def remove_quotations(str)
  if str.starts_with?('"')
    str = str.slice(1..-1)
  end
  if str.ends_with?('"')
    str = str.slice(0..-2)
  end
end 

It is without regexps and starts_with?/end_with? are nicely readable.

它没有regexp和starts_with?/end_with?可读得很漂亮。

#5


3  

It frustrates me that strip only works on whitespace. I need to strip all kinds of characters! Here's a String extension that will fix that:

让我沮丧的是,条带只能在空格上工作。我需要去除所有的角色!这里有一个字符串扩展,它将解决这个问题:

class String
  def trim sep=/\s/
    sep_source = sep.is_a?(Regexp) ? sep.source : Regexp.escape(sep)
    pattern = Regexp.new("\\A(#{sep_source})*(.*?)(#{sep_source})*\\z")
    self[pattern, 2]
  end
end

Output

输出

'"foo,bar"'.trim '"'         # => "foo,bar"
'"foo,bar'.trim '"'          # => "foo,bar"
'foo,bar"'.trim '"'          # => "foo,bar"
'foo,bar'.trim '"'           # => "foo,bar"

'  foo,bar'.trim             # => "foo,bar"
'afoo,bare'.trim /[aeiou]/   # => "foo,bar"

#6


1  

I wanted the same but for slashes in url path, which can be /test/test/test/ (so that it has the stripping characters in the middle) and eventually came up with something like this to avoid regexps:

我想要的是相同的,但是对于斜杠的url路径,它可以是/测试/测试/测试/(这样它就有了中间的剥离字符),最终产生了这样的东西来避免regexp:

'/test/test/test/'.split('/').reject(|i| i.empty?).join('/')

Which in this case translates obviously to:

在这种情况下,很明显的意思是:

 '"foo,bar"'.split('"').select{|i| i != ""}.join('"')

or

'"foo,bar"'.split('"').reject{|i| i.empty?}.join('"')

#7


0  

Regexs can be pretty heavy and lead to some funky errors. If you are not dealing with massive strings and the data is pretty uniform you can use a simpler approach.

Regexs可能非常重,会导致一些奇怪的错误。如果你没有处理大量的字符串并且数据是统一的,你可以使用一种更简单的方法。

If you know the strings have starting and leading quotes you can splice the entire string:

如果你知道字符串有起始和前引语,你可以将整个字符串拼接在一起:

string  = "'This has quotes!'"
trimmed = string[1..-2] 
puts trimmed # "This has quotes!"

This can also be turned into a simple function:

这也可以变成一个简单的函数:

# In this case, 34 is \" and 39 is ', you can add other codes etc. 
def trim_chars(string, char_codes=[34, 39])
    if char_codes.include?(string[0]) && char_codes.include?(string[-1])
        string[1..-2]
    else
        string
    end
end

#8


-1  

Assuming that quotes can only appear at the beginning or end, you could just remove all quotes, without any custom method:

假设引号只能出现在开头或结尾,你可以删除所有的引号,不需要任何自定义方法:

'"foo,bar"'.delete('"')

#9


-1  

You can strip non-optional quotes with scan:

你可以带扫描的非可选引号:

'"foo"bar"'.scan(/"(.*)"/)[0][0]
# => "foo\"bar"