【问题标题】:Rails: Remove substring from the string if in arrayRails:如果在数组中,则从字符串中删除子字符串
【发布时间】:2014-11-29 03:14:37
【问题描述】:

我知道我可以轻松remove a substring from a string

现在我需要从字符串中删除每个子字符串,如果子字符串在数组中。

arr = ["1. foo", "2. bar"]
string = "Only delete the 1. foo and the 2. bar"

# some awesome function
string = string.replace_if_in?(arr, '')
# desired output => "Only delete the and the"

所有的删除函数都可以调整字符串,例如subgsubtr,...只需要一个单词作为参数,而不是数组。但是我的数组有超过 20 个元素,所以我需要一个比使用 sub 20 次更好的方法。

遗憾的是,这不仅仅是删除单词,而是删除整个子字符串为1. foo

我将如何尝试?

【问题讨论】:

    标签: ruby arrays string


    【解决方案1】:

    您可以使用接受正则表达式的gsub,并将其与Regexp.union 结合使用:

    string.gsub(Regexp.union(arr), '')
    # => "Only delete the  and the "
    

    【讨论】:

      【解决方案2】:

      如下:

       arr = ["1. foo", "2. bar"]
       string = "Only delete the 1. foo and the 2. bar"
      
       arr.each {|x| string.slice!(x) }
       string # => "Only delete the  and the " 
      

      一个扩展的东西,这还允许您使用regexp 服务字符裁剪文本,例如\.(Uri 的答案也允许):

       string = "Only delete the 1. foo and the 2. bar and \\...."
       arr = ["1. foo", "2. bar", "\..."]
      
       arr.each {|x| string.slice!(x) }
       string # => "Only delete the  and the  and ."
      

      【讨论】:

      • 骰子决定接受你 ;) 谢谢大家的帮助!
      • 请注意,如果string = "Only delete the 1. foo and the 2. bar and another 2. bar?",我们得到=> "Only delete the and the and another 2. bar?" 这就是我们想要的吗?我不知道。冠军,你不妨澄清一下。
      【解决方案3】:

      在数组元素上使用#gsub 和#join

      您可以通过对数组元素调用#join 来使用#gsub,并使用正则表达式交替运算符将它们连接起来。例如:

      arr = ["foo", "bar"]
      string = "Only delete the foo and the bar"
      string.gsub /#{arr.join ?|}/, ''
      #=> "Only delete the  and the "
      

      然后,您可以以任何您认为合适的方式处理留下的额外空间。当您想要审查单词时,这是一种更好的方法。例如:

      string.gsub /#{arr.join ?|}/, '<bleep>'
      #=> "Only delete the <bleep> and the <bleep>"
      

      另一方面,如果您需要关心空格,split/reject/join 可能是更好的方法链。做某事的方法总是不止一种,而且您的里程可能会有所不同。

      【讨论】:

      • 使用join 不是最佳选择,因为它不会转义每个元素中的文本1. foo 也会匹配11 foo...
      • 仅供参考:1. foo 将在所有答案中匹配 11. foo,所以这个答案并不逊色
      猜你喜欢
      • 1970-01-01
      • 2018-11-01
      • 2015-04-23
      • 2011-10-25
      • 1970-01-01
      • 2019-09-08
      • 1970-01-01
      相关资源
      最近更新 更多