我有一串连续的相同字符,例如:“ aaabbc”,我想将它们分组为一个数组:[“ aaa”,“ bb”,“ c”]。
我已经尝试使用Hash解决它,并且确实有效,但是现在我想知道是否可以使用split和regex解决。
这是我根据SO的另一个答案所做的:
"aaabbc".split(/\\b([a-z])\\1+\\b/)
Run Code Online (Sandbox Code Playgroud)
但这给了我数组中的初始字符串:
["aaabbc"]
Run Code Online (Sandbox Code Playgroud)
不要给每组相同的连续字符用逗号分隔:
["aaa", "bb", "c"]
"aaabbc".gsub(/(.)\1*/).to_a
#=> ["aaa", "bb", "c"]
Run Code Online (Sandbox Code Playgroud)
当没有给出块时,它将使用String#gsub的形式,在这种情况下,将返回一个枚举数。实际上,这种形式gsub与字符串替换无关。枚举器仅生成匹配项。当存在捕获组时,它克服了String#scan的限制。
正则表达式显示为“匹配任何字符,将其保存在捕获组1中,然后匹配零个或多个等于捕获组1内容的字符”。
该答案不使用split,而是提供另一种选择。您可以利用Enumerable#chunk_while:
"aaabbc".each_char.chunk_while(&:==).map(&:join)
#=> ["aaa", "bb", "c"]
Run Code Online (Sandbox Code Playgroud)
This first pulls apart the string into a list of characters, then it compares the consecutive elements using ==. This creates an array of character arrays. Finally you convert each character array back to a string using join.