Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I match repeated characters?

Tags:

ruby

How do I find repeated characters using a regular expression?

If I have aaabbab, I would like to match only characters which have three repetitions:

aaa
like image 949
loganathan Avatar asked Dec 27 '22 08:12

loganathan


1 Answers

Try string.scan(/((.)\2{2,})/).map(&:first), where string is your string of characters.

The way this works is that it looks for any character and captures it (the dot), then matches repeats of that character (the \2 backreference) 2 or more times (the {2,} range means "anywhere between 2 and infinity times"). Scan will return an array of arrays, so we map the first matches out of it to get the desired results.

like image 159
Chris Heald Avatar answered Jan 10 '23 13:01

Chris Heald