Matching characters
Character classes
Goal: Match one character from a set with [...], ranges and shorthands · 9 min
A character class in square brackets matches one character out of a set.
[aeiou]matches one vowel.- A range uses a hyphen:
[0-9]is a digit,[a-z]a lowercase letter,[A-Za-z]any letter of the basic alphabet. - Negation with a caret as the first character:
[^0-9]matches anything except a digit. - Inside brackets most metacharacters lose their power:
[.]is just a dot,[+*]is a plus or a star.
Frequent sets have shorthands:
| shorthand | meaning | equals |
|---|---|---|
\d | digit | [0-9] |
\w | word character: letter, digit, underscore | [A-Za-z0-9_] |
\s | whitespace: space, tab, line break | |
\D \W \S | the opposite of each |
Note that \w in JavaScript covers only ASCII letters: "ä" and "ß" are not matched. For German text use an explicit class such as [A-Za-zÄÖÜäöüß].
Worked example: Matching a hex digit
- A hex digit is 0-9 or a-f or A-F.
- Combine three ranges in one class:
[0-9a-fA-F]. - Test: "7" and "c" match, "g" does not.
const re = /[0-9a-fA-F]/;
console.log(re.test("7"), re.test("c"), re.test("g"));Output:
true true false