Execute Program

Regular Expressions: Parens

Welcome to the Parens lesson!

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

  • This regex seems to match strings of exactly one "a" or exactly one "b". But that's not all it matches!

  • >
    /^a|b$/.test('a');
    Result:
    truePass Icon
  • >
    /^a|b$/.test('b');
    Result:
    truePass Icon
  • >
    /^a|b$/.test('xa');
    Result:
    falsePass Icon
  • >
    /^a|b$/.test('ax');
    Result:
    truePass Icon
  • Why did /^a|b$/ accept the string "ax"? It makes more sense if we parenthesize the regex. (Parentheses group operators together, like in other programming languages.)

  • >
    /(^a)|(b$)/.test('xa');
    Result:
    falsePass Icon
  • >
    /(^a)|(b$)/.test('ax');
    Result:
    truePass Icon
  • When we say /^a|b$/, it means the same as /(^a)|(b$)/. We might prefer it to mean /^(a|b)$/, but it is the way it is. Fortunately, adding those parentheses ourselves will help.

  • >
    /^(a|b)$/.test('a');
    Result:
    truePass Icon
  • >
    /^(a|b)$/.test('xa');
    Result:
    falsePass Icon
  • >
    /^(a|b)$/.test('ax');
    Result:
    falsePass Icon
  • >
    /^(a|b)$/.test('xb');
    Result:
    falsePass Icon
  • >
    /^(a|b)$/.test('b');
    Result:
    truePass Icon
  • >
    /^(a|b)$/.test('bx');
    Result:
    falsePass Icon
  • Imagine that we have a system that can read images. But it can only read JPGs, PNGs, and PDFs; anything else makes it crash. We want a regex that will accept images based on their filename.

  • >
    /^(jpg|png|pdf)$/.test('jpg');
    Result:
    truePass Icon
  • >
    /^(jpg|png|pdf)$/.test('jpeg');
    Result:
    falsePass Icon
  • >
    /^(jpg|png|pdf)$/.test('png');
    Result:
    truePass Icon
  • >
    /^(jpg|png|pdf)$/.test('pdf');
    Result:
    truePass Icon
  • As in math or normal programming, parentheses can "factor out" common elements.

  • >
    /^(jpg|p(ng|df))$/.test('jpg');
    Result:
    truePass Icon
  • >
    /^(jpg|p(ng|df))$/.test('jpeg');
    Result:
    falsePass Icon
  • >
    /^(jpg|p(ng|df))$/.test('pdf');
    Result:
    truePass Icon
  • >
    /^(jpg|p(ng|df))$/.test('png');
    Result:
    truePass Icon
  • >
    /^(jpg|p(ng|df))$/.test('p');
    Result:
    falsePass Icon
  • We can use operators on parenthesized groups. In this example, the + matches strings of one or more characters. The (a|b) requires each of those characters to be an "a" or a "b".

  • >
    /^(a|b)+$/.test('aaaaab');
    Result:
    truePass Icon
  • >
    /^(a|b)+$/.test('bababa');
    Result:
    truePass Icon
  • >
    /^(a|b)+$/.test('');
    Result:
    falsePass Icon
  • Either side of a | can be empty. This regex means "exactly the letter a, or the empty string".

  • >
    /^(a|)$/.test('a');
    Result:
    truePass Icon
  • >
    /^(a|)$/.test('');
    Result:
    truePass Icon
  • >
    /^(a|)$/.test('aa');
    Result:
    falsePass Icon