Regex Metacharacters

Regular expression engines (PCRE, POSIX, Perl, etc.) define shorthand character classes that match common sets of characters. These are the most frequently used metacharacters:

ClassEquivalentMatches
\d[0-9]Digit
\D[^0-9]Non-digit
\w[0-9a-zA-Z_]Word character (letter, digit, underscore)
\W[^0-9a-zA-Z_]Non-word character
\s[ \t\n\r\f\v]Whitespace (including line breaks)
\S[^ \t\n\r\f\v]Non-whitespace

Critical gotcha

\w includes the underscore _ but does not include the hyphen -.

This is a common source of bugs when validating usernames, hostnames, or file names. For example, ^\w+$ will reject my-file.txt (because of the -) but accept my_file.txt (because _ is a word character).

Dialect differences

  • POSIX basic/extended — Use [:digit:], [:alpha:], [:alnum:], [:space:] inside bracket expressions (e.g. [:digit:]).
  • PCRE / Perl\d, \w, \s are native. In UTF-8 mode, \w may match Unicode letters depending on the engine and flags.
  • GNU grep — Supports \w, \s, \b (word boundary), \B (non-word-boundary) in both BRE and ERE modes.

Related: grep (pattern matching tool), findstr (Windows equivalent), sed-single-line-find-replace (regex in practice).

Sources

See also