Magnus
Magnus

Reputation: 121

Finding patterns in numbers while parsing Ruby

If I have a list of numbers like
112536
523534
241255
233345
212121
in a text file.

And I want to find any number where a digit is repeated three times in a row or a 2-digit set is repeated three times in a row, how would I do that?

The dumb way to do it is something like

while (line = f.gets)
   g.puts line if line =~ /111/
   g.puts line if line =~ /222/
   g.puts line if line =~ /333/  
   etc...

But that's obviously not efficient. Is there a simpler way to do this?

Upvotes: 2

Views: 229

Answers (1)

Bart Kiers
Bart Kiers

Reputation: 170138

Try the pattern:

(\d)\1\1

which repeats a single digit 3 times and:

(\d\d)\1\1

will repeat two digits 3 times. Combining them would look like:

(\d\d?)\1\1

A rubular demo: http://rubular.com/r/J8VQ3SSGnT

The parenthesis around the \d\d? will save that single- or double digit in match group 1, and then that group is repeated twice (\1\1).

Upvotes: 5

Related Questions