23

In Vim, the character class \s matches any whitespace character. When I'm using those special characters in groups e.g. [\s\w] it does not match any single whitespace or word character, it does match s or w.

How does one use character classes inside groups?

1
  • 9
    Unlike some implementations of regular expression engines, Vim's doesn't seem to support that notation. [[:space:][:alnum:]_] can be used to approximate the collection of \s and \w, though. Jul 31, 2015 at 14:36

2 Answers 2

16

That's not a group, it's a range, and in Vim you can't use character classes (although it's possible in other regex implementations, e.g. in python). You'll have to use an alternation instead:

/\(\w\|\s\)

or:

/\v(\s|\w)

(or, the solution proposed by Peter Lewerin).

3
  • 2
    Just because one can construct an invalid range in a character class doesn't mean that it shouldn't be possible to use something like \s in a character class. Vim's regex implementation happens to have made that choice, but other implementations allow you to use [\s].
    – jamessan
    Jul 31, 2015 at 16:46
  • @VanLaser If you edit the answer with this info ([\s] is a possibilty in other regex-implementations but not in vim) i'll accept your answer!
    – JHK
    Aug 2, 2015 at 5:23
  • (all right, added)
    – VanLaser
    Aug 2, 2015 at 14:53
15

Unlike some implementations of regular expression engines, Vim's doesn't seem to support that notation ([\s\w]) in collections. One can use POSIX character class expressions, though.

  • [:blank:] is the same as \s.
  • [:space:] matches a greater number of whitespace characters than \s does, and seems to be equivalent to \_s.
  • [:alnum:] approximates \w, but does not match the underscore (_).

So the collection you wanted could be written as [[:blank:][:alnum:]_] or [[:space:][:alnum:]_].

I haven't verified this by testing, but it is documented in :h regexp, :h /character-classes, and :h /collection.

Portability note: In other regex engines, \s is typically the same as [:space:] (or \_s) is in Vim.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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