Specify Exact Number of Matches

Specify Exact Number of Matches
0.0 0

#1

Tell us what’s happening:
What am i missing? i match for exactly 4, it passes on RegExr, why is this throwing error for more than 4 m’s?
Error: Your regex should not match “Timber” with 30 m’s in it.

Your code so far


let timStr = "Timmmmber";
let timRegex = /m{4}/; // Change this line
let result = timRegex.test(timStr);

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/regular-expressions/specify-exact-number-of-matches/


#2

Because you didn’t account for repeating characters. In essence your regex says, give me exactly 4 m’s consecutively. Which leads to this issue

Ti [mmmm][mmmm][mmmm][…]ber.

That matches groups of 4 m’s. I know, the docs aren’t really clear on that.

You need to qualify the regex to return no more than 4 m’s.


#3

Thanks… i’m searching the internet high and low for any reference to this. The lesson and examples are regarding the {4} notation. And it works as expected in several regex tools. If anyone has a link to how to do ‘no more than’… even though {4"} supposed to be exactly :rofl: Any direction would be greatly appreciated.


#4

I’ll give you one last hint and a spoiler to my solution. Look into these:

  • positive lookahead
    • Matches a group after the main expression without including it in the result.
  • negative lookahead
    • Specifies a group that can not match after the main expression (if it matches, the result is discarded).
  • negated set
    • Match any character that is not in the set.

Solution:

let timRegex = /[^m]m{4}(?!m)/

// [^m]  is a negated set. It will only return a match if the 
//       letter 'm' is not the first character in the entire regex match

// m{4}  matches exactly 4 m's

// (?!m) is a negative lookahead that returns a match 
//       only if the matched text before it is not followed by an 'm'