Quantifiers in JavaScript Regular Expressions (Live Playground)
Quantifiers in JavaScript regular expressions enable you to specify how many times a character or character class should appear in a string. In this tutorial, we'll explore the different types of quantifiers and how to use them.
Basic Quantifiers
Here are the basic quantifiers:
?
: Matches zero or one occurrence of the preceding character or character class.*
: Matches zero or more occurrences of the preceding character or character class.+
: Matches one or more occurrences of the preceding character or character class.
Example:
const zeroOrOneDigit = /\d?/; // matches zero or one digit
const anyDigits = /\d*/; // matches any number of digits, including none
const atLeastOneDigit = /\d+/; // matches one or more digits
Exact Quantifier
To match an exact number of occurrences, use curly braces {}
with a number inside:
const threeDigits = /\d{3}/; // matches exactly three digits
const fourLetters = /[a-zA-Z]{4}/; // matches exactly four letters
Range Quantifiers
To specify a range of occurrences, use curly braces with two numbers separated by a comma:
const twoToFourDigits = /\d{2,4}/; // matches between two and four digits
const threeToFiveLetters = /[a-zA-Z]{3,5}/; // matches between three and five letters
To specify a minimum number of occurrences without an upper limit, use a comma followed by an empty space:
const atLeastTwoDigits = /\d{2,}/; // matches at least two digits
const atLeastThreeLetters = /[a-zA-Z]{3,}/; // matches at least three letters
Greedy and Lazy Quantifiers
By default, quantifiers are greedy, meaning they try to match as many characters as possible. To make a quantifier lazy, add a question mark ?
after the quantifier. A lazy quantifier matches as few characters as possible while still satisfying the pattern:
const greedyMatch = /<.+>/; // matches everything between the first '<' and the last '>'
const lazyMatch = /<.+?>/; // matches everything between each pair of '<' and '>'
Conclusion
Quantifiers are essential in JavaScript regular expressions to specify how many times a character or character class should appear in a string. We discussed basic quantifiers, such as ?
, *
, and +
, as well as exact and range quantifiers using curly braces. We also covered the difference between greedy and lazy quantifiers. Mastering quantifiers will help you create powerful and flexible patterns in your regular expressions.