Execute Program

Regular Expressions: Maybe

Welcome to the Maybe lesson!

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

  • The ? operator matches a character zero or one times, but not more than one.

  • >
    /^a?$/.test('a');
    Result:
    truePass Icon
  • >
    /^a?$/.test('');
    Result:
    truePass Icon
  • >
    /^a?$/.test('b');
    Result:
    falsePass Icon
  • >
    /^a?$/.test('aa');
    Result:
    falsePass Icon
  • The ? operator affects whatever is immediately before it. For example, in ab?, the ? operators only affects "b", not "a". We say that it binds tightly.

  • >
    /^ab?$/.test('a');
    Result:
    truePass Icon
  • >
    /^ab?$/.test('b');
    Result:
    falsePass Icon
  • >
    /^ab?$/.test('ab');
    Result:
    truePass Icon
  • Often, part of a string is optional. For example, US telephone numbers sometimes have area codes. But for local calls, no area code is necessary. For optional strings like this, we can use the ? operator.

  • >
    /^555-?555-5555$/.test('555-555-5555');
    Result:
    truePass Icon
  • Unfortunately, this regex isn't quite right. The ? only applies to the "-" character before it, so only that character is optional. All of the other characters are required.

  • >
    /^555-?555-5555$/.test('555555-5555');
    Result:
    truePass Icon
  • To make ? include more characters, we can group them using parentheses. Then we apply the ? to the whole group.

  • >
    /^(555-)?555-5555$/.test('555-555-5555');
    Result:
    truePass Icon
  • >
    /^(555-)?555-5555$/.test('555-5555');
    Result:
    truePass Icon
  • >
    /^(555-)?555-5555$/.test('555555-5555');
    Result:
    falsePass Icon