Search code examples
regexposix

Can I do a negation of a POSIX bracket expression?


I know I can search for something matching a space with the POSIX bracket expression [[:space:]]. Can I do a search for something not matching a space using a POSIX bracket expression? In particular, the characters it should match include letters, and parentheses (().

[[:graph:]] looks somewhat vague:

[[:graph:]] - Non-blank character (excludes spaces, control characters, and similar)


Solution

  • You confuse two things here: a bracket expression and a POSIX character class. The outer [...] is a bracket expression, and it can be negated with a ^ that immediately follows [. A POSIX character class is a [:+name+:] construct that only works inside bracket expressions.

    So, in your case, [[:space:]] pattern is a bracket expression containing just 1 POSIX character class that matches a whitespace:

    • [ - opening a bracket expression
      • [:space:] - a POSIX character class for whitespace
    • ] - closing bracket of the bracket expression.

    To negate it, just add the ^ as in usual NFA character classes: [^[:space:]].

    Note I deliberately differentiate the terms "bracket expression", "POSIX character class" and "character class" since POSIX and common NFA regex worlds adhere to different terminology.