Regular Expressions - Specify Exact Number of Matches

Tell us what’s happening:
Hi everyone. This is my first post. Sorry in advance if that question has been already asked. I searched for it but didn’t find anything. So here I am :slight_smile:

I was curious about that exercise. How about just matching a string that contains exactly 4 'a’s.

I don’t understand why a string with more than 4 ‘a’ also returns “true”.

If a string contains other characters after the 'a’s, then it works as intended. But why?

Thanks

Your code so far

let example1 = "aaaaa";
let example2 = "aaaa";
let example3 = "aaa";
let regex = /a{4}/; // Change this line
console.log(regex.test(example1));
console.log(regex.test(example2));
console.log(regex.test(example3));

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:106.0) Gecko/20100101 Firefox/106.0

Challenge: Regular Expressions - Specify Exact Number of Matches

Link to the challenge:

you can see the pattern matching in action on this site
https://regex101.com/

Note that the pattern wants to find 4 a’s
it does not want to find exactly four a’s

1 Like

test method checks if match is possible on string and returns true or false.
let regex = /a{4}/
match "aaaa" , "aaaaa", "aaaa....", "bbbaaaaa", as long as there are 4 "a" on string it matches.

1 Like

Thanks a lot for your answer.s

What I don’t understand, is that by having something like this:

let example1 = "haaaaah";
let example2 = "haaaah";
let example3 = "haaah";
let regex = /ha{4}h/; // Change this line
console.log(regex.test(example1)); // --> false
console.log(regex.test(example2)); // --> true
console.log(regex.test(example3)); // --> false

…it matches perfectly with exactly 4 'a’s.

that is not because of the a{4} but more because of the h at the start and the end forcing the matching to find anything that has one h, 4 as and one h

if you remove the ending h for example then it will match
haaaaaaaaaa too

2 Likes

Oh I see now.

A solution for the first code I posted:

let example1 = "aaaaa";
let example2 = "aaaa";
let example3 = "aaa";
let regex = /a{4}/; // Change this line
console.log(regex.test(example1));
console.log(regex.test(example2));
console.log(regex.test(example3));

…would be to use the following regex instead:

let regex = /^aa{2}a$/; // Change this line

I get it now :slight_smile:

Thanks a lot.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.