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 matchesregular expressionTry it in Dotstar →
Each class is one character, so gr[ae]y matches both spellings of grey, and nothing longer:
/gr[ae]y/g2 matchesgrey, gray, graeyTry 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, #12ab34Try 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 matchesalice,bob,,charlieTry 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:
\da digit,\Danything else\wa “word” character: a letter, a digit or an underscore;\Wanything else\swhite space: a space, a tab, a line break;\Sanything else
/\w+/g6 matchesuser_42 logged in at 09:15Try 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 matchesnaïve caféTry it in Dotstar →
Here is the same pattern in other engines:
/\w+/gin each enginenaïve café
| JavaScript, Java, PCRE2, Go, RE2 | na ve caf |
|---|---|
| Python, .NET, Rust, Perl, ICU, Swift | naï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 engine5⍽kg
| JavaScript, Python, .NET | 5⍽kg |
|---|---|
| Java, PCRE2, Go | no match |
Run in each engine itself, as Dotstar’s Compare runs them, when this page was checked.
/[[:alpha:]]+/gin each enginealpha]
| PCRE2, Go, Rust, Ruby, Perl, POSIX ERE | alpha |
|---|---|
| JavaScript, Python | a] |
Run in each engine itself, as Dotstar’s Compare runs them, when this page was checked.