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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With