TutreNews Learn

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:

shorthandmeaningequals
\ddigit[0-9]
\wword character: letter, digit, underscore[A-Za-z0-9_]
\swhitespace: space, tab, line break
\D \W \Sthe 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

  1. A hex digit is 0-9 or a-f or A-F.
  2. Combine three ranges in one class: [0-9a-fA-F].
  3. 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