Execute Program

Regular Expressions: Constrained Repetition

Welcome to the Constrained Repetition lesson!

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

  • Sometimes we need text to be of a certain length. We could repeat . to enforce length.

  • >
    /^.....$/.test('1234');
    Result:
    falsePass Icon
  • >
    /^.....$/.test('12345');
    Result:
    truePass Icon
  • >
    /^.....$/.test('123456');
    Result:
    falsePass Icon
  • This is awkward, especially if we want to match exactly, say, 20 characters. Fortunately, there's a better way: {curly braces}.

  • >
    /^.{5}$/.test('1234');
    Result:
    falsePass Icon
  • >
    /^.{5}$/.test('12345');
    Result:
    truePass Icon
  • >
    /^.{5}$/.test('123456');
    Result:
    falsePass Icon
  • We can repeat anything in this way, not just .

  • >
    /^(a|b){3}$/.test('aaa');
    Result:
    truePass Icon
  • >
    /^(a|b){3}$/.test('bba');
    Result:
    truePass Icon
  • >
    /^(a|b){3}$/.test('ab');
    Result:
    falsePass Icon
  • By adding a comma, we can specify a range of allowed lengths.

  • >
    /^.{2,3}$/.test('1');
    Result:
    falsePass Icon
  • >
    /^.{2,3}$/.test('12');
    Result:
    truePass Icon
  • >
    /^.{2,3}$/.test('123');
    Result:
    truePass Icon
  • >
    /^.{2,3}$/.test('1234');
    Result:
    falsePass Icon
  • We can also specify "n or more characters" by omitting the second number. For example, .{8,} means "at least eight characters".

  • >
    /^[fho]{3,}$/.test('of');
    Result:
    falsePass Icon
  • >
    /^[fho]{3,}$/.test('off');
    Result:
    truePass Icon
  • >
    /^[fho]{3,}$/.test('hoof');
    Result:
    truePass Icon
  • In some regex systems, .{,5} means "at most five characters". Unfortunately, that's not true in JavaScript's regexes. JavaScript won't tell us about our mistake either. Instead, the {,5} gets interpreted as a literal string!

  • >
    /^.{,5}$/.test('12345');
    Result:
    falsePass Icon
  • >
    // Watch out: JavaScript regexes are weird in this case!
    /^.{,5}$/.test('.{,5}');
    Result:
    truePass Icon
  • This is bizarre, but not a big problem. If we need five or fewer characters, we can say .{0,5}.

  • >
    /^.{0,5}$/.test('1234');
    Result:
    truePass Icon
  • >
    /^.{0,5}$/.test('12345');
    Result:
    truePass Icon
  • >
    /^.{0,5}$/.test('123456');
    Result:
    falsePass Icon