2

That is, given a POSIX regex X, what POSIX regex is the complementary of X? (in a more detailed way: how to get regex X' that matches all strings that are not matched by X, but doesn't match any string that is matched by X)

If this is not available in POSIX, is there a common extension that has it?

  • PCREs (perl) can do that. – Hauke Laging Jul 2 '13 at 12:30
  • @HaukeLaging they can? How? Do you mean $foo!~/bar/? – terdon Jul 2 '13 at 12:53
  • The problem doesn't usually come up, as in most environments you can just if not match instead of if match so you use the same regexp. Your question would be easier to answer if you had a specific use case. – frostschutz Jul 2 '13 at 13:11
  • @terdon I am not familiar with PCRE. I just know they can but not how. If I knew I would have mentioned it. My fuzzy memory believes that ? is involved (like in bash extglob). – Hauke Laging Jul 2 '13 at 13:17
  • @frostschutz That doesn't help you at all if you need the negation within a regex. – Hauke Laging Jul 2 '13 at 13:18
2

I believe you could try (?:(?!X).) with PCRE, It definitely works when X is a string but I am not a 100% sure that it would work all the time when X is a regex.

echo "dust mite" | grep -P '^(?:(?!abc).)*$'
dust mite

echo "dust abc mite" | grep -P '^(?:(?!abc).)*$'
echo "dust mite" | grep -P '^(?:(?!abc(x+y)).)*$'
dust mite

echo "dust abcxxxxy mite" | grep -P '^(?:(?!abc(x+y)).)*$'
  • I gave it a few tries and it seems to work too! Thanks a lot. I find it strange there isn't a simpler way though! It looks to me like it would be the easiest thing to implement... and very useful - guaranteeing this would be possible everywhere using just POSIX regex, without having to rely on other particular command constructs (like grep's -v) – ricab Jul 3 '13 at 10:43
  • BTW, I would vote you up, but I don't have enough rep, sorry – ricab Jul 3 '13 at 10:44
  • Traditional regexes are just a simple state machine. There is an abundance of background information on the Internet which explains fairly well how a regex fundamentally works. Once you understand that, it will also be fairly obvious why the Perl (and thus PCRE) extension is not standard. – tripleee Jul 3 '13 at 11:30
  • 1
    @tripleee: I did not ask why PCRE is not standard, I ask why wasn't a simple a complement operator included in available regexes (even in PCRE). The way I see it, regexes are fundamentally based on Finite State Machines (FSM) and it would be a trivial thing to get a complementary FSM for any given regex FSM. So, perhaps from the abundant information on how regex fundamentally work you could select the pieces that would actually contribute anything to the discussion? – ricab Jul 10 '13 at 13:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.