Execute Program

Regular Expressions: Word Boundaries

Welcome to the Word Boundaries lesson!

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

  • When using a regular expression to search for a word, we usually don't want to match those letters inside another word.

  • >
    /cat/.test("I couldn't locate Mr. Meow.");
    Result:
    truePass Icon
  • The word 'locate' contains 'cat', so this sentence matches. But in this case, we only intended to match the actual word 'cat'. Regexes provide a way to do this using the word boundary \b:

  • >
    /\bcat\b/.test('It was difficult to locate, but');
    Result:
    falsePass Icon
  • >
    /\bcat\b/.test('the cat returned.');
    Result:
    truePass Icon
  • \b only matches where a word character is next to a non-word character. (Remember that word-characters are letters, numbers and underscores.)

  • >
    /\bcat\b/.test("var cat_name = 'Mr. Meow';");
    Result:
    falsePass Icon
  • >
    /\bcat\b/.test("Where's the cat's toy?");
    Result:
    truePass Icon
  • >
    /\bcat\b/.test('cat-like reflexes');
    Result:
    truePass Icon
  • In the last example above, the "c" in "cat" was also the first character in the string. Still, that string matched /\bcat\b/. It matches because the beginning and end of the string are considered non-word characters.

  • Like most character classes, \b can be negated by capitalizing it. \B only matches between two word characters. It's pronounced "non-word-boundary".

  • >
    /\Bcat\B/.test('The cat over there');
    Result:
    falsePass Icon
  • >
    /\Bcat\B/.test('concatenate');
    Result:
    truePass Icon
  • \B can be used to find out if a word has 'cat' in particular places, which could help win Scrabble games.

  • If you'd like to find words that contain "cat", but don't end with "cat":

  • >
    /cat\B/.test('publication');
    Result:
    truePass Icon
  • >
    /cat\B/.test('wildcat');
    Result:
    falsePass Icon
  • >
    /cat\B/.test('catenary');
    Result:
    truePass Icon
  • Or words that contain "cat" only in the middle:

  • >
    /\Bcat\B/.test('cathode');
    Result:
    falsePass Icon
  • >
    /\Bcat\B/.test('muscat');
    Result:
    falsePass Icon
  • >
    /\Bcat\B/.test('hecatomb');
    Result:
    truePass Icon