Execute Program

Regular Expressions: Boundaries

Welcome to the Boundaries lesson!

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

  • Often, we want to match text at the beginning and end of strings. We'll use boundaries for that. The first is ^, which means beginning of string.

  • >
    /^cat/.test('cat');
    Result:
    truePass Icon
  • >
    /^cat/.test('cats are cute');
    Result:
    truePass Icon
  • >
    /^cat/.test('I like cats');
    Result:
    falsePass Icon
  • >
    /^cat/.test('cats like dogs');
    Result:
    truePass Icon
  • >
    /^cat/.test('dogs like cats');
    Result:
    falsePass Icon
  • The second boundary is $, which means end of string.

  • >
    /cat$/.test('a dog');
    Result:
    falsePass Icon
  • >
    /cat$/.test('a cat');
    Result:
    truePass Icon
  • >
    /cat$/.test('cats');
    Result:
    falsePass Icon
  • Usually, we want to match an entire string. Most regexes should include these boundaries, ^ and $.

  • >
    /^a$/.test('a');
    Result:
    truePass Icon
  • >
    /^a$/.test('the letter a');
    Result:
    falsePass Icon
  • >
    /^a$/.test('a cat');
    Result:
    falsePass Icon
  • To match only the empty string, we can smash the ^ and $ together.

  • >
    /^$/.test('a');
    Result:
    falsePass Icon
  • >
    /^$/.test(' ');
    Result:
    falsePass Icon
  • >
    /^$/.test('');
    Result:
    truePass Icon
  • If we use the wrong boundaries, there's no error. The regex always returns false.

  • >
    /$cat^/.test('cat');
    Result:
    falsePass Icon
  • If we use boundaries in the wrong place, the regex will always return false.

  • >
    /cat$s/.test('cats');
    Result:
    falsePass Icon
  • >
    /cat^s/.test('cat');
    Result:
    falsePass Icon
  • One final note about the ^ and $ boundaries. Above, we said that they match the beginning and end of strings. In most cases, that's true, but only because most regex engines default to "single-line mode": a regex only considers the first line in the string.

  • Regex engines also have "multi-line mode", where a single regex can match any part of a multi-line string. In that mode, ^ means "beginning of line" and $ means "end of line." They can match characters that are at the beginning or end of a line, even if those characters aren't at the beginning or end of the entire string.

  • Multi-line regexes are their own topic, so we won't cover them in detail here. But in practice, you may see ^ referred to as both "beginning of line" and "beginning of string", and likewise for $.