The POSIX rules for getting ]
into a character class are a little arcane, but they make sense when you think about it hard.
For a positive (non-negated) character class, the ]
must be the first character:
[]and]
This recognizes any character a
, n
, d
or ]
as part of the character class.
For a negated character class, the ]
must be the first character after the ^
:
[^]and]
This recognizes any character except a
, n
, d
or ]
as part of the character class.
Otherwise, the first ]
after the [
marks the end of the character class. Inside a character class, most of the normal regex special characters lose their special meaning, and others (notably -
minus) acquire special meanings. (If you want a -
in a character class, it has to be 'first' or last, where 'first' means 'after the optional ^
and only if ]
is not present'.)
In your examples:
[^][()]
— this is a negated character class that recognizes any character except[
,]
,(
or)
, but[^[]()]
— this is a negated character class that recognizes any character except[
, followed by whatever()
symbolizes in the regex family you're using, and]
which represents itself.