loganathan
loganathan

Reputation: 6156

How do I match repeated characters?

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

Upvotes: 4

Views: 2308

Answers (1)

Chris Heald
Chris Heald

Reputation: 62668

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.

Upvotes: 10

Related Questions