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:
false
>
/^.....$/.test('12345');Result:
true
>
/^.....$/.test('123456');Result:
false
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:
false
>
/^.{5}$/.test('12345');Result:
true
>
/^.{5}$/.test('123456');Result:
false
We can repeat anything in this way, not just
.>
/^(a|b){3}$/.test('aaa');Result:
true
>
/^(a|b){3}$/.test('bba');Result:
true
>
/^(a|b){3}$/.test('ab');Result:
false
By adding a comma, we can specify a range of allowed lengths.
>
/^.{2,3}$/.test('1');Result:
false
>
/^.{2,3}$/.test('12');Result:
true
>
/^.{2,3}$/.test('123');Result:
true
>
/^.{2,3}$/.test('1234');Result:
false
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:
false
>
/^[fho]{3,}$/.test('off');Result:
true
>
/^[fho]{3,}$/.test('hoof');Result:
true
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:
false
>
// Watch out: JavaScript regexes are weird in this case!/^.{,5}$/.test('.{,5}');Result:
true
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:
true
>
/^.{0,5}$/.test('12345');Result:
true
>
/^.{0,5}$/.test('123456');Result:
false