1

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.

3

Character classes such as \s are not acceptable inside a [...] group (with or without the ^, but character class expressions such as [:space:] actually are. So you can use the following:

/\[[^\[\][:space:]]\+]

This will correctly match [first] and [second], besides [third] and [fourth] in your original regular expression.

Note that there's a small difference between \s and [:space:]. While the former only matches space and tab, the latter matches all whitespace characters: space, tab, CR, NL, vertical tab and form feed. For most cases (including this one), that doesn't really affect the end result. (In fact, you could argue you get a better regex from [:space:], since it matches more characters that should qualify as whitespace.)

There are similar [:...:] sequences for other corresponding matches, for example [:keyword:] which is the same as \k. But some, such as \w, don't have a direct counterpart, but it's actually just [:alnum:] plus underscore, so [[:alnum:]_] should do it, or [^[:alnum:]_] to match \W.

| improve this answer | |

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.