I want to write a regex that finds words contained in brackets, like [word]
. The words are not allowed to contain spaces or the characters [
or ]
.
I tried with
\[[^\[\]\s]\+]
But applied to the string
'foo [first] bar [second] baz [third] and [fourth]'
it only finds [third]
and [fourth]
.
I don't understand why. What is wrong with the regex? It is not totally wrong as it still finds some matches. But not all I would expect.
EDIT: Ok, I found it. \s
is not working as expected. I intended to use it as a character class, but it is obiously interpreted as the separate characters \
and s
. As first
and second
both contain the s
they don't match.
Now: How do I match character classes inside a []
construct?
(I updated the title accordingly.)
EDIT2: Regex in Vi: How does one use character classes inside groups? (e.g. [\s\w]) basically askes the same. But there is no answer about how to exclude character classes.