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?

  • 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. – Peter Lewerin Jul 31 '15 at 14:36
  • @PeterLewerin Please post that as an answer. – Christopher Bottoms Aug 24 '15 at 14:30
  • @ChristopherBottoms: done. – Peter Lewerin Aug 24 '15 at 17: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:




(or, the solution proposed by Peter Lewerin).

| improve this answer | |
  • 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 '15 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! – John H. K. Aug 2 '15 at 5:23
  • (all right, added) – VanLaser Aug 2 '15 at 14:53

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.

| 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.