Javascript in 100 bits

Course by zooboole,

Last Updated on 2025-01-28 08:04:00

Lesson 64 - Quantifiers in Regular Expressions

Introduction

Quantifiers in regular expressions allow you to specify how many times a character, group, or character class should appear in a match.

Common Quantifiers

Quantifier Description Example
* Matches 0 or more times /ab*c/ matches "ac", "abc", "abbc", etc.
+ Matches 1 or more times /ab+c/ matches "abc", "abbc", "abbbc", etc. but not "ac".
? Matches 0 or 1 time /ab?c/ matches "ac" or "abc".
{n} Matches exactly n times /a{3}/ matches "aaa" but not "aa" or "aaaa".
{n,} Matches at least n times /a{2,}/ matches "aa", "aaa", "aaaa", etc.
{n,m} Matches between n and m times /a{2,4}/ matches "aa", "aaa", or "aaaa", but not "a" or "aaaaa".

Example Usage

const regex1 = /a{2,4}/;
console.log(regex1.test("a"));      // false
console.log(regex1.test("aa"));     // true
console.log(regex1.test("aaa"));    // true
console.log(regex1.test("aaaa"));   // true
console.log(regex1.test("aaaaa"));  // false

const regex2 = /h.*o/;
console.log(regex2.test("hello"));  // true
console.log(regex2.test("ho"));     // true
console.log(regex2.test("hxyzzo")); // true

Try Your Hand

Write a regex that matches a string containing the letter "x" exactly 3 times in a row. Test it in JavaScript.

const regex = /________/;  // Fill in the blank
console.log(regex.test("xx"));   // false
console.log(regex.test("xxx"));  // true
console.log(regex.test("xxxx")); // true, but does it match exactly 3 times?

Summary

  • * matches 0 or more times.
  • + matches 1 or more times.
  • ? matches 0 or 1 time.
  • {n} matches exactly n times.
  • {n,} matches at least n times.
  • {n,m} matches between n and m times.

Quantifiers are powerful when used correctly in pattern matching.