1

I want to check with regex if the word link appears twice in a sentence.

The sentence goes: "This link is invalid. Try the link below." --> here I need the regex to check if "link" appears twice.

This is my first time trying regex and I only understood the grouping so far like \b(link)\b. With this I can check if the word link even appears but I need to know if it appears twice.

How can I achieve this?

BlueCat
  • 673
  • 4
  • 16
  • 27
  • @tobias_k It shows that `.*` can be used to match any chars between two same words. `\blink\b.*\blink\b` will do for the time being, unless there is something else. – Wiktor Stribiżew Aug 14 '18 at 13:04
  • @WiktorStribiżew Never mind, I read the question as check whether _any_ word appears twice, but if OP just wants to check for "link", the same can be used as for "http". – tobias_k Aug 14 '18 at 13:05

1 Answers1

1

Try this one:

\b(link)\b(?=.*\b\1\b)

This gives you the first occurrence of the duplicate word.

Tested it with your sentence here: https://regex101.com/r/2zGSKj/2

A shorter solution without groups would simply be

\blink\b.*\blink\b

Tested it here: https://regex101.com/r/2zGSKj/3

NaN
  • 7,441
  • 6
  • 32
  • 51