Character classes in regular expressions (denoted by square brackets []) represent sets of characters where the pattern matches any single character from that set. Since character classes are sets, specifying the same character multiple times is redundant and often indicates a programming error.

Common mistakes include:

Examine each duplicate character to determine the intended behavior:

Note that simply removing | characters from character classes is rarely the correct fix. Instead, analyze the pattern to understand what the author intended to match.

Example 1: Confusing character classes with groups

The pattern [password|pwd] does not match "password" or "pwd" as intended. Instead, it matches any single character from the set {p, a, s, w, o, r, d, |}. Note that | has no special meaning inside character classes.

To fix this problem, the regular expression should be rewritten to /(password|pwd) =/.

Example 2: CSS unit matching

The pattern r?e[m|x] appears to be trying to match "rem" or "rex", but actually matches "re" followed by any of the characters {m, |, x}. The correct pattern should be r?e(m|x) or r?e[mx].

Similarly, v[h|w|min|max] should be v(h|w|min|max) to properly match "vh", "vw", "vmin", or "vmax".

  • Mozilla Developer Network: JavaScript Regular Expressions.
  • MDN: Character Classes - Details on how character classes work.
  • MDN: Groups and Ranges - Proper use of grouping with parentheses.