Split string by multiple delimiters

后端 未结 5 1469
迷失自我
迷失自我 2020-12-08 01:52

I want to split a string by whitespaces, , and \' using a single ruby command.

  1. word.split will split by white spaces

相关标签:
5条回答
  • 2020-12-08 02:08
    x = "one,two, three four" 
    
    new_array = x.gsub(/,|'/, " ").split
    
    0 讨论(0)
  • 2020-12-08 02:28
    word = "Now is the,time for'all good people"
    word.split(/[\s,']/)
     => ["Now", "is", "the", "time", "for", "all", "good", "people"] 
    
    0 讨论(0)
  • 2020-12-08 02:28

    You can use a combination of the split method and the Regexp.union method like so:

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

    You can even use regex patters in the delimiters.

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

    This solution has the advantage of allowing totally dynamic delimiters or any length.

    0 讨论(0)
  • 2020-12-08 02:30

    Regex.

    "a,b'c d".split /\s|'|,/
    # => ["a", "b", "c", "d"]
    
    0 讨论(0)
  • 2020-12-08 02:31

    Here is another one :

    word = "Now is the,time for'all good people"
    word.scan(/\w+/)
    # => ["Now", "is", "the", "time", "for", "all", "good", "people"]
    
    0 讨论(0)
提交回复
热议问题