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?
1 Answer 1
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.
answered Jul 1, 2022 at 17:27
Sign up to request clarification or add additional context in comments.
4 Comments
Mathéo RB
For some reason when I execute this regex as:
function detectPatterns(string){ let regex = /(.*?)( ?1円)+/g; if(string.match(regex)) return true; else return false; }
it returns true allways for example with "Hello" or "Hello I'm Mathéo". But when I test it out in regex101 or regexr it's correct. Did I mispell something?lemon
I have updated the answer so that it will catch exactly only repeated characters from start to end, yet at least one. Does it solve your problem?
Mathéo RB
Yep! That works perfectly. I have another related question with this, as there exist some words that by default are detected by this expression. Do you have any kind of idea that could help me to exempt these words without actually writing them one by one?
lemon
Can you craft some examples? If you are talking about "Palindromic" words, then you are forced to assume there's always a space between your words, and in that case you would remove the
?
after the space inside the regex. If there's no way for you to tell where a word ends and another starts, then there may nothing possible for that to be solved with a regex straight (as regex see words just as strings of characters).lang-js
pattern
specially? e.g.:a a
is not a repeating pattern just likeaxa
is not a repeating pattern. Buta a
is, just likeaxax
is.