Exclusive Or in Regular Expression

后端 未结 13 1772
小鲜肉
小鲜肉 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:28

    If your regex language supports it, use negative lookaround:

    (?

    This will match "foo" or "bar" that is not immediately preceded or followed by "foo" or "bar", which I think is what you wanted.

    It's not clear from your question or examples if the string you're trying to match can contain other tokens: "foocuzbar". If so, this pattern won't work.

    Here are the results of your test cases ("true" means the pattern was found in the input):

    foo: true
    bar: true
    foofoo: false
    barfoo: false
    foobarfoo: false
    barbar: false
    barfoofoo: false
    

提交回复
热议问题