I am trying to build a regex that matches all consecutive identical digits in a string. For example, given the string '111221'
I would like matches of ['111', '22', '1']
.
My current regex is /(\d)\1*/
which works fine with String#match
but, of course, only returns the first match in the string.
'111221'.match /(\d)\1*/ #=> #<MatchData "111" 1:"1">
The method given in Ruby global match regexp? to get global matches is to use String#scan
but its behaviour is not what I would expect, presumably because of the capturing group:
'111221'.scan /(\d)\1*/ #=> [["1"], ["2"], ["1"]]
whereas in other languages, for example Javascript, it works fine:
'111221'.match(/(\d)\1*/g) //=> [ "111", "22", "1" ]
Is there something fundamentally wrong with my regex or some Ruby functionality that I am missing?