Regular Expression find same word repeatead on a line

156 views Asked by At

I try to create REGEX that will find a word that can appear for example 3 times on a line. for example I have "My cat is here and the second cat and a third cat are there."

So I create this Regex :

^(\b\w{3,}\b).*\1

It works for 2 times appearing. But If add this to want more than 3 times :

^(\b\w{3,}\b).*\1{3,}

It doesn't work. So I try to find any word that is at least 3 letters long and can appear at least 3 times on the same line.

Someone have an idea ?

thanks

1

There are 1 answers

2
Avinash Raj On

Your regex must be,

(\b\w{3,}\b).*\1.*\1

\1{3,} will search for 3 or more times of captured word

OR

(\b\w{3,}\b)(?:.*\1){2,}

.* matches any character, zero or more times. \1 refers the chars present inside the first capturing group. So (?:.*\1){2,} will search for the captured string to be appear more than twice. If yes, then it will do matching. For 3 or more, just change the number 2 present inside the repeatation quantifier to 3. {2,} repeats the previous token (?:.*\1) two or more times.