DEV Community

Cover image for Regex: finding repetitions
Kirill Artamonov
Kirill Artamonov

Posted on

4

Regex: finding repetitions

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!

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay