regular expression - match word only once in line

后端 未结 3 1016
一个人的身影
一个人的身影 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:27

    A simple option is this (using the multiline flag and not dot-all):

    ^(?!.*\bhello\b.*\bhello\b).*\bhello\b.*$
    

    First, check you don't have 'hello' twice, and then check you have it at least once.
    There are other ways to check for the same thing, but I think this one is pretty simple.

    Of course, you can simple match for \bhello\b and count the number of matches...

提交回复
热议问题