DEV Community

loading...
Cover image for Regex: finding repetitions

Regex: finding repetitions

Kirill Artamonov
・1 min read

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)
Enter fullscreen mode Exit fullscreen mode

Let's test it out:

console.log(repetitions('bookkeeper')) 
// expected output: Array ["oo", "kk", "ee"]
console.log(repetitions('длинношеее'))
// expected output: Array ["нн", "еее"]
Enter fullscreen mode Exit fullscreen mode

That's it. Happy coding and regexing!

Discussion (0)

Forem Open with the Forem app