How to split a string of repeated characters with uneven amounts? Ruby

后端 未结 2 1200
梦毁少年i
梦毁少年i 2021-01-15 06:13

If I have a string such as \"aabbbbccffffdeffffgg\" and I wanted to split the string into this array: [\"aa\", \"bbbb\", \"cc\", \"ffffd\", \"e\", \"ffff\", \

相关标签:
2条回答
  • 2021-01-15 06:17

    Here is a non-regexp version

    str = "aabbbbccffffdeffffgg"
    p str.chars.chunk(&:itself).map{|x|x.last.join} #=> ["aa", "bbbb", "cc", "ffffd", "e", "ffff", "gg"]
    
    0 讨论(0)
  • 2021-01-15 06:37

    You can use a regex with a back reference and the scan() method:

    str = "aabbbbccffffdeffffgg"
    groups = []
    str.scan(/((.)\2*)/) { |x| groups.push(x[0]) }
    

    groups will look like this afterwards:

    ["aa", "bbbb", "cc", "ffffd", "e", "ffff", "gg"]
    
    0 讨论(0)
提交回复
热议问题