Execute Program

Regular Expressions: Literals

Welcome to the Literals lesson!

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

  • Regular expressions (regexes) are patterns that describe strings. We might write a regex for filenames ending in ".jpg". Or we might write one that recognizes phone numbers. We'll use JavaScript's regexes, but it's OK if you don't know JavaScript.

  • We can ask whether a regex matches a given string: /a/.test('cat'). The regex /a/ means "any string containing an a". We asked about 'cat', which contains an "a", so we'll get true back.

  • >
    /a/.test('a');
    Result:
    truePass Icon
  • >
    /a/.test('b');
    Result:
    falsePass Icon
  • >
    /a/.test('xax');
    Result:
    truePass Icon
  • Regexes are case-sensitive, so "a" and "A" are different characters.

  • >
    /A/.test('a');
    Result:
    falsePass Icon
  • >
    /A/.test('A');
    Result:
    truePass Icon
  • Multi-character regexes test that the characters appear together. They have to be adjacent, with no other characters between them.

  • >
    /cat/.test('cart');
    Result:
    falsePass Icon
  • >
    /cat/.test('cat');
    Result:
    truePass Icon
  • >
    /cat/.test('the cat there');
    Result:
    truePass Icon
  • Spaces are treated as normal characters. If they're in the regex, they'll have to be in the matched string too. Likewise for _, -, and some other punctuation. (But some punctuation has special meaning, which we'll see soon.)

  • >
    /a cat/.test('that is a cat');
    Result:
    truePass Icon
  • >
    /_/.test('happy-cat');
    Result:
    falsePass Icon
  • >
    /_/.test('happy_cat');
    Result:
    truePass Icon