【问题标题】:Split string by multiple delimiters通过多个分隔符拆分字符串
【发布时间】:2013-10-30 19:37:54
【问题描述】:

我想使用单个 ruby​​ 命令按空格分割字符串,,'

  1. word.split 将被空格分隔;

  2. word.split(",") 将被, 拆分;

  3. word.split("\'") 将被' 拆分。

如何同时做这三个?

【问题讨论】:

  • Karan,您可能已经注意到,只要单引号在双引号之间,您就不必转义它。

标签: ruby string split


【解决方案1】:
word = "Now is the,time for'all good people"
word.split(/[\s,']/)
 => ["Now", "is", "the", "time", "for", "all", "good", "people"] 

【讨论】:

  • 大家好,感谢过去两年的所有支持,但请不要忽视@oldergod 的回答。
【解决方案2】:

正则表达式。

"a,b'c d".split /\s|'|,/
# => ["a", "b", "c", "d"]

【讨论】:

  • 我之前错过了你的回答。我更喜欢它,因为它读起来更好(使用“或”)。您忘记包含|\s,可能是因为您误读了问题。
【解决方案3】:

您可以像这样使用split 方法和Regexp.union 方法的组合:

delimiters = [',', ' ', "'"]
word.split(Regexp.union(delimiters))
# => ["Now", "is", "the", "time", "for", "all", "good", "people"]

您甚至可以在分隔符中使用正则表达式模式。

delimiters = [',', /\s/, "'"]
word.split(Regexp.union(delimiters))
# => ["Now", "is", "the", "time", "for", "all", "good", "people"]

此解决方案的优点是允许使用完全动态的分隔符或任何长度。

【讨论】:

  • 见鬼,伙计!谢谢。这是迄今为止最好的解决方案,imo。
  • 这对于不熟悉 Regex 的其他开发人员来说是最易读的。 ?
  • 没有那么简洁,但对疲倦的眼睛很容易。
【解决方案4】:

这是另一个:

word = "Now is the,time for'all good people"
word.scan(/\w+/)
# => ["Now", "is", "the", "time", "for", "all", "good", "people"]

【讨论】:

    【解决方案5】:
    x = "one,two, three four" 
    
    new_array = x.gsub(/,|'/, " ").split
    

    【讨论】:

    • 我喜欢你的方法,是的,它提供了正确的解决方案。
    【解决方案6】:

    我知道这是一个旧线程,但我只是偶然发现它并认为我会留下另一个答案。我个人喜欢避免使用regex,因为我觉得它很难阅读,而且它几乎总是比使用其他内置方法慢。因此,除了上述的正则表达式解决方案,我还会考虑使用以下方法:

    word.gsub(",", " ").gsub("'", " ").split
    

    第一个gsub 将所有出现的, 替换为space。第二个 gsub 将所有出现的 ' 替换为 space。这会在所有所需位置产生whitespace。然后 split 不带任何参数,只是在空格上拆分。

    它只比前面提到的一些解决方案快一点,但我相信它比提到的任何其他解决方案都要快。

    【讨论】:

      猜你喜欢
      • 2017-03-21
      • 2013-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-02
      • 1970-01-01
      • 2011-11-29
      • 1970-01-01
      相关资源
      最近更新 更多