Execute Program

Regular Expressions: Character Sets

Welcome to the Character Sets lesson!

This lesson is shown as static text below. However, it's designed to be used interactively. Click the button below to start!

  • In a character set, characters and ranges can be mixed in any order. This regex is equivalent to /[g]|[c-e]|[a]/.

  • >
    /[gc-ea]/.test('a');
    Result:
    truePass Icon
  • >
    /[gc-ea]/.test('b');
    Result:
    falsePass Icon
  • >
    /[gc-ea]/.test('c');
    Result:
    truePass Icon
  • >
    /[gc-ea]/.test('d');
    Result:
    truePass Icon
  • >
    /[gc-ea]/.test('h');
    Result:
    falsePass Icon
  • We can also negate the whole character set, even if it's complex.

  • >
    /[^gc-ea]/.test('a');
    Result:
    falsePass Icon
  • >
    /[^gc-ea]/.test('d');
    Result:
    falsePass Icon
  • >
    /[^gc-ea]/.test('b');
    Result:
    truePass Icon
  • If a character set ever gives you trouble, you can always break it up. For example, /[hbd-fa]/ can be thought of as /(h|b|[d-f]|a)/. This trick works for anything in regexes. Most regex features are syntactic sugar for simple features like |.

  • Special characters aren't special inside a character set. For example, "." means a literal "." and "$" is a literal "$".

  • >
    /[a$]/.test('$');
    Result:
    truePass Icon
  • >
    /[a$]/.test('a');
    Result:
    truePass Icon
  • >
    /[a$]/.test('^');
    Result:
    falsePass Icon
  • >
    /^[a$]$/.test('ab');
    Result:
    falsePass Icon
  • The ^ is only special if it's the first character in the set. There, it means "negate this set". But a ^ anywhere else in the set is just another literal character.

  • >
    /[^b]/.test('b');
    Result:
    falsePass Icon
  • >
    /[b^]/.test('b');
    Result:
    truePass Icon
  • >
    /[b^]/.test('^');
    Result:
    truePass Icon
  • >
    /[^^]/.test('b');
    Result:
    truePass Icon
  • >
    /[^^]/.test('^');
    Result:
    falsePass Icon