vimtricks.wiki Concise Vim tricks, one at a time.

How do I use POSIX character classes like [:alpha:] and [:digit:] in Vim search patterns?

Answer

[[:alpha:]]

Explanation

Vim's regex engine supports POSIX character classes inside bracket expressions, giving you locale-aware, readable alternatives to manual character ranges like [a-zA-Z]. These classes are especially useful for writing patterns that work correctly across different locales and encodings.

How it works

POSIX classes are written inside double brackets [[:class:]] — a bracket expression [...] containing the POSIX class [:class:]:

Class Matches
[[:alpha:]] Letters (a-z, A-Z, locale-specific)
[[:digit:]] Decimal digits 0-9
[[:alnum:]] Letters and digits
[[:lower:]] Lowercase letters
[[:upper:]] Uppercase letters
[[:space:]] Whitespace (space, tab, newline, etc.)
[[:punct:]] Punctuation characters
[[:print:]] Printable characters
[[:blank:]] Space and tab only

Example

Find all function-like tokens starting with an uppercase letter:

/[[:upper:]][[:alnum:]_]\+

Find lines containing only whitespace:

/^[[:space:]]*$

Delete trailing punctuation from lines:

:%s/[[:punct:]]\+$//

Tips

  • The double bracket is required: [[:alpha:]] not [:alpha:] alone
  • Mix POSIX classes with literal chars in one bracket set: [[:alpha:]_] matches letters and underscore
  • Vim also provides shorthand atoms: \a = [[:alpha:]], \d = [[:digit:]], \s = [[:space:]], \l = [[:lower:]], \u = [[:upper:]]
  • POSIX classes are locale-aware, so they can match accented characters (e.g., é, ü) when locale supports it
  • See :help character-classes for the full reference

Next

How do I encode and decode JSON data in Vimscript for configuration and plugin development?