DEV Community

SCDan0624
SCDan0624

Posted on

Javascript regex part 6 specify number of matches

How to specify upper and lower number of matches

Previously when we would look for a specific number of matches we would use the * sign for zero or more matches and the + for one or more matches. You can also specify a certain range of patterns with the {} sign which are called quantity specifiers.

For example what if we wanted to only match the letter o between 3 and 7 times? Here is how you would code it out:

let firstOh = 'oooh';
let secondOh = 'oh';
let searchForO = /o{3,9}h/;

searchForO.test(firstOh) // returns true
searchForO.test(secondOh) // returns false
Enter fullscreen mode Exit fullscreen mode

How to specify lower number of matches only

If you want to only specify the lower number with no upper limit you use the same syntax as above without a second number after the comma:

let firstOh = 'oooh';
let secondOh = 'oh';
let thirdOh = 'ooooooooooooooooooooooooh'
let searchForO = /o{3,}h/;

searchForO.test(firstOh) // returns true
searchForO.test(secondOh) // returns false
searchForO.test(thirdOh) // returns true
Enter fullscreen mode Exit fullscreen mode

How to specify an exact number of matches

If you want to specify only an exact number of matches you will have just one number between {}:

et firstLow = 'Looow';
let secondLow = 'Low';
let thirdLow = 'Loooooooooooooooooooooooow'
let searchForO = /Lo{3}w/;

searchForO.test(firstLow) // returns true
searchForO.test(secondLow) // returns false
searchForO.test(thirdLow) // returns false
Enter fullscreen mode Exit fullscreen mode

Top comments (0)