2

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?

Community
  • 1
  • 1
Jon G
  • 61
  • 4
  • 3
    Have you seen [Match sequences of consecutive characters in a string](http://stackoverflow.com/questions/8498689/match-sequences-of-consecutive-characters-in-a-string)? You have an identical input string to that question, which is a remarkable coincidence – Michael Berkowski Dec 13 '15 at 14:00
  • That's bizarre! I hadn't seen it, and my example string comes from http://adventofcode.com/day/10 which the question obviously predates by a good few years. The accepted solution is identical to my workaround too. I was hoping for a cleaner solution but I'd be happy to see this closed as a duplicate. – Jon G Dec 13 '15 at 14:16

0 Answers0