Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to find repeated word in a string with regex

I have an string like codecodecodecodecode…… I need to find repeated word in that string

I found I way but the regular expression it always return half of repeated part I want just

^(.*)\1+$

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

at the group(1) I want to see just "code"

>Solution :

If it is greedy, it will first match till the end of the line, and will then backtrack until it can repeat 1 or more times till the end of the string, and for an evenly divided part like this of 4 words, you can capture 2 words and match the same 2 words with the backreference \1

If you have 5 words like codecodecodecodecode as in your example there will be a single group, as the only repetition it can do until the end of the string is 5 repetitions.

The quantifier should be non greedy (and repeat 1+ times to not match an empty string) to match as least as possible characters that can be repeated to the right till the end of the string.

^(.+?)\1+$

regex demo

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading