Finding repeating characters in a string - whether it's a Run-length encoding exercise on exercism.io, a task during a technical interview, or even a production feature like validating created users passwords - is easily implemented using a simple regular expression.
The regex feature that we'll need is called "backreference". While the examples below are in JavaScript, this feature is defined as part of the POSIX standard, so it supported in various other languages.
Let's get started:
const repetitions = input => input.match(/(.)\1+/g)
Let's test it out:
console.log(repetitions('bookkeeper'))
// expected output: Array ["oo", "kk", "ee"]
console.log(repetitions('длинношеее'))
// expected output: Array ["нн", "еее"]
That's it. Happy coding and regexing!
Top comments (0)