Execute Program

Regular Expressions: Basic Character Classes

Welcome to the Basic Character Classes lesson!

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

  • Some sets of characters occur together frequently. For example, we often need to recognize numbers (the digits 0-9). We can use \d for that. It recognizes 0, 1, ..., 8, 9.

  • We use \s to recognize whitespace: spaces, newlines (\n), tabs (\t), etc.

  • There are more of these, but we'll start with \s and \d. These are called character classes.

  • >
    /\s/.test(' ');
    Result:
    truePass Icon
  • >
    /\s/.test('\n');
    Result:
    truePass Icon
  • >
    /\s/.test('');
    Result:
    falsePass Icon
  • >
    /\s/.test('x\ty'); /* \t is a tab character */
    Result:
    truePass Icon
  • >
    /\s/.test('cat');
    Result:
    falsePass Icon
  • >
    /\d/.test('0');
    Result:
    truePass Icon
  • >
    /\d/.test('9');
    Result:
    truePass Icon
  • >
    /\d/.test('a');
    Result:
    falsePass Icon
  • Making these character classes upper-case negates them. For example, \d is all digits. But \D is any character that isn't a digit.

  • >
    /\D/.test('0');
    Result:
    falsePass Icon
  • >
    /\S/.test(' ');
    Result:
    falsePass Icon
  • >
    /\S/.test('0');
    Result:
    truePass Icon
  • A character class matches only one character in the string. If we want to match multiple characters, we can use + or *.

  • >
    /^\d$/.test('1000');
    Result:
    falsePass Icon
  • >
    /^\d*$/.test('3000');
    Result:
    truePass Icon
  • >
    /^\d*$/.test('1000 cats');
    Result:
    falsePass Icon
  • >
    /^\d*$/.test('cats');
    Result:
    falsePass Icon
  • >
    /^\d*$/.test('');
    Result:
    truePass Icon