Regex: Find consecutive characters
11 March 2022 (Updated 28 August 2022)
On this page
TLDR
'bbbaaabaaaa'.match(/(\w)(\1+)/g)
// Output: ['bbb', 'aaa', 'aaaa']
Explanation
(\w)
: Match any alphanumeric character and store this in a capture group (think a temporary variable).(\1+)
: match one or more characters that are the same as what was captured in the first capture group.
This example is written using String.match
in JavaScript but the regex should be reusable across other languages. A Ruby example might look like:
'bbbaaabaaaa'.scan(/(\w)(\1+)/).map(&:join)
# Output: ['bbb', 'aaa', 'aaaa']
Tagged:
Regex
Thanks for your comment 🙏. Once it's approved, it will appear here.
Leave a comment