regular expression - match word only once in line

后端 未结 3 1014
一个人的身影
一个人的身影 2020-12-19 03:06

Case:

  1. ehello goodbye hellot hello goodbye
  2. ehello goodbye hello hello goodbye

I want to match line 1 (only has \'hello\' once!) DO NOT w

3条回答
  •  清酒与你
    2020-12-19 03:40

    A generic regex would be:

    ^(?:\b(\w+)\b\W*(?!.*?\b\1\b))*\z
    

    Altho it could be cleaner to invert the result of this match:

    \b(\w+)\b(?=.*?\b\1\b)
    

    This works by matching a word and capturing it, then making sure with a lookahead and a backreference that it does/not follow anywhere in the string.

提交回复
热议问题