Skip to content
Advertisement

Find and detect a pattern in a string

I’m looking for a function that detects repeated patterns on a string, for example, if the input is:

var string = "HelloHelloHelloHelloHelloHello";
var string2 = "Hello this is a repeated pattern Hello this is a repeated pattern Hello this is a repeated pattern Hello this is a repeated pattern";

it should return true as there are many times repeated “Hello” or “Hello this is a repeated pattern”

I have tried something like this:

function detectPattern(string) {
    string = string.replace(/s+/g,"_");
    return /(S)(1{15,})/g.test(string);
}

but that will only detect if the text contains the same character many times.

Any idea or suggestion?

Advertisement

Answer

A regex that would work is the following:

^(.+?)( ?1)+$

This will match:

  • ^: start of string
  • (.+?): the least amount of characters (at least one), followed by
  • ( ?1)+: an optional space and the very same characters of the first group, multiple times
  • $: end of string

In order to extract your repeated pattern, it’s sufficient to extract the content of Group 1.

Check the demo here.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement