Exclusive Or in Regular Expression

后端 未结 13 1744
小鲜肉
小鲜肉 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条回答
  •  Happy的楠姐
    2020-12-05 10:50

    You haven't specified behaviour regarding content other than "foo" and "bar" or repetitions of one in the absence of the other. e.g., Should "food" or "barbarian" match?

    Assuming that you want to match strings which contain only one instance of either "foo" or "bar", but not both and not multiple instances of the same one, without regard for anything else in the string (i.e., "food" matches and "barbarian" does not match), then you could use a regex which returns the number of matches found and only consider it successful if exactly one match is found. e.g., in Perl:

    @matches = ($value =~ /(foo|bar)/g)  # @matches now hold all foos or bars present
    if (scalar @matches == 1) {          # exactly one match found
      ...
    }
    

    If multiple repetitions of that same target are allowed (i.e., "barbarian" matches), then this same general approach could be used by then walking the list of matches to see whether the matches are all repeats of the same text or if the other option is also present.

提交回复
热议问题