我想知道如何在Ruby中拆分二进制字符串。 我想拆分前一个字符与下一个字符不同的字符串。
例如,如果我有字符串
@s = "aaaabbabbaa"
我想创建一个字符串数组
@array[0] = "aaaa"
@array[1] = "bb"
@array[2] = "a"
@array[3] = "bb"
@array[4] = "aa"
我怎么能这样做?
答案 0 :(得分:3)
Enumerable#chunk这样做,但它在Enumerable上定义 - 和String不包括Enumerable。将其转换为字符数组(并将它们粘合回字符串),如:
s = "aaaabbabbaa"
p array = s.chars.chunk(&:itself).map{|a| a.last.join} #=>["aaaa", "bb", "a", "bb", "aa"]
答案 1 :(得分:2)
您可以使用scan
的正则表达式:
@array = @s.scan(/((.)\2*)/).map(&:first)
#=> ["aaaa", "bb", "a", "bb", "aa"]
答案 2 :(得分:2)
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"]
通过使用两个外观,在正则表达式上拆分时不会丢失任何字符。
答案 3 :(得分:1)
str = "aaaabbabbaa"
p str.chars.chunk_while(&:==).map(&:join)
输出:["aaaa", "bb", "a", "bb", "aa"]