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 check for duplicate word with REGEX

I have a following string:

var string = "(one)(two)(one)(five)";

I would like to know how can I check that for duplicates with REGEX. It is supposed to return a Boolean value. For my example, it should return true.

Thank you!

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

>Solution :

You can use backreferences to accomplish this.

https://www.regular-expressions.info/refcapture.html

\1 through \9 Substituted with the text matched between the 1st through 9th numbered capturing group.

Therefore, something like this should do the trick:

\((.+?)\).*\(\1\)

This works by capturing the text in your first parentheses block, and then looking to see if that same text appears in any other parentheses.

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