2

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?

1 Answer 1

5

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).

Sign up to request clarification or add additional context in comments.

5 Comments

Great, thanks! From that, I already figured out the second example, which is (\d\d)\1\1
You forgot the |(\d\d)\2\2 part.
And if I want to find 223322, I can with (\d)\1(\d)\2(\d)\1
@mu, ah, yeah, missed that part. Thanks. I shortened it a little though: (\d\d?)\1\1
@Magnus, yeah you seem to get the hang of it. Good!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.