Learn regular expressions · Lesson 4

Character classes

A character class matches one character, any of those listed between square brackets. [aeiou] is one vowel:

/[aeiou]/g7 matches
regular expression
Try it in Dotstar →

Each class is one character, so gr[ae]y matches both spellings of grey, and nothing longer:

/gr[ae]y/g2 matches
grey, gray, graey
Try it in Dotstar →

Ranges

A hyphen between two characters is everything from one to the other: [0-9] is a digit, [a-z] a lowercase ASCII letter, and they combine: [A-Za-z0-9_]. A hyphen first or last is a plain hyphen, so [-+0-9] is a sign or a digit.

/[0-9A-F]+/g3 matches
#FF8800, #12ab34
Try it in Dotstar →

Without the i flag, [0-9A-F] leaves out lowercase a to f, which is why only part of the second colour matched.

Negation

A ^ right after the opening bracket turns the class around: [^0-9] is any character that is not a digit, spaces and line breaks included.

/[^,]+/g3 matches
alice,bob,,charlie
Try it in Dotstar →

That’s the usual way to say “up to the next comma”, and it can’t run past one.

What’s special inside

Inside brackets most of the special characters are plain: [.*+?] is a dot, a star, a plus or a question mark. What stays special is ] (it ends the class), \ (it escapes), ^ at the start and - between two characters. Escape them to mean them: [\]\\] is a bracket or a backslash.

Shorthands

Some classes are so common they have names:

  • \d a digit, \D anything else
  • \w a “word” character: a letter, a digit or an underscore; \W anything else
  • \s white space: a space, a tab, a line break; \S anything else
/\w+/g6 matches
user_42 logged in at 09:15
Try it in Dotstar →

They work inside brackets too: [\w.-]+ is a run of word characters, dots and hyphens, as in a host name.

Which characters count?

Here the engines disagree, and it matters as soon as the text isn’t English. Is é a \w? Is ٣ (Arabic three) a \d? In JavaScript, no: \w and \d are ASCII only, even with the u flag, while \s takes Unicode’s white space too, such as the no-break space. So \w+ breaks two French words into three pieces:

/\w+/g3 matches
naïve café
Try it in Dotstar →

Here is the same pattern in other engines:

/\w+/gin each engine
naïve café
JavaScript, Java, PCRE2, Go, RE2na ve caf
Python, .NET, Rust, Perl, ICU, Swiftnaïve café

Run in each engine itself, as Dotstar’s Compare runs them, when this page was checked.

And \s against a no-break space, the kind a word processor puts between a number and its unit (shown as ⍽):

/5\s?kg/gin each engine
5⍽kg
JavaScript, Python, .NET5⍽kg
Java, PCRE2, Gono match

Run in each engine itself, as Dotstar’s Compare runs them, when this page was checked.

/[[:alpha:]]+/gin each engine
alpha]
PCRE2, Go, Rust, Ruby, Perl, POSIX EREalpha
JavaScript, Pythona]

Run in each engine itself, as Dotstar’s Compare runs them, when this page was checked.