Exclusive Or in Regular Expression

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

    If you want a true exclusive or, I'd just do that in code instead of in the regex. In Perl:

    /foo/ xor /bar/
    

    But your comment:

    Matches: "foo", "bar" nonmatches: "foofoo" "barfoo" "foobarfoo" "barbar" "barfoofoo"

    indicates that you're not really looking for exclusive or. You actually mean "Does /foo|bar/ match exactly once?"

    my $matches = 0;
    while (/foo|bar/g) {
      last if ++$matches > 1;
    }
    
    my $ok = ($matches == 1)
    

提交回复
热议问题