How to find consecutive characters with Regex

Aug 17, 2020
'bbbaaabaaaa'.match(/(\w)(\1+)/g)
# Output: ['bbb', 'aaa', 'aaaa']

This works by first matching against any alphanumeric character (\w) and storing this in a capture group (think a temporary variable).

We then use (\1+) to tell Regex to match only those characters that have the same exact character occurring immediately after it at least once. The \1 refers to our previously matched capture group (\w) whilst the + means that the same character must be repeated at least once.

This example is written using String.match in JavaScript but the Regex should be more or less reusable across other languages.

A Ruby example might look like:

'bbbaaabaaaa'.scan(/(\w)(\1+)/).map(&:join)
# Output: ['bbb', 'aaa', 'aaaa']