简体   繁体   中英

Ruby split binary string where the previous character is different from the next one

I wonder how could I split a binary string in Ruby. I want to split the string where the previous character is different from the next one.

for example if i have the string

    @s = "aaaabbabbaa"

I would like to create an array of strings

    @array[0] = "aaaa"
    @array[1] = "bb"
    @array[2] = "a"
    @array[3] = "bb"
    @array[4] = "aa"

How could i do this?

Enumerable#chunk does that, but its defined on Enumerable - and String does not include Enumerable. Transform it into an Array of chars (and glue them back to strings) , like:

s = "aaaabbabbaa"
p array = s.chars.chunk(&:itself).map{|a| a.last.join} #=>["aaaa", "bb", "a", "bb", "aa"]

You could use a regular expression with scan :

@array = @s.scan(/((.)\2*)/).map(&:first)
#=> ["aaaa", "bb", "a", "bb", "aa"]
str = "aaaabbabbaa"

r = /
    (?<=(.))  # match any character in capture group 1, in positive lookbehind
    (?!\1)    # do not match capture group 1, negative lookahead
    /x        # free-spacing regex definition mode

str.split(r)
  #=> ["aaaa", "a", "bb", "b", "a", "a", "bb", "b", "aa", "a"]

By using two lookarounds no characters are lost when splitting on the regular expression.

using Enumerable#chunk_while

str = "aaaabbabbaa"
p str.chars.chunk_while(&:==).map(&:join)

Output : ["aaaa", "bb", "a", "bb", "aa"]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM