Exclusive Or in Regular Expression

后端 未结 13 1762
小鲜肉
小鲜肉 2020-12-05 10:06

Looking for a bit of regex help. I\'d like to design an expression that matches a string with \"foo\" OR \"bar\", but not both \"foo\" AND \"b

13条回答
  •  半阙折子戏
    2020-12-05 10:30

    I tried with Regex Coach against:

    x foo y
    x bar y
    x foobar y
    

    If I check the g option, indeed it matches all three words, because it searches again after each match.
    If you don't want this behavior, you can anchor the expression, for example matching only on word boundaries:

    \b(foo|bar)\b
    

    Giving more context on the problem (what the data looks like) might give better answers.

提交回复
热议问题