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!

>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.

Leave a Reply