Finding patterns in numbers while parsing Ruby
If I have a list of numbers like
112536 523534 24125开发者_JAVA百科5 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?
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
).
精彩评论