Reuse patterns and the Carat symbol

Tell us what’s happening:

Use capture groups in reRegex to match a string that consists of only the same number repeated exactly three times separated by single spaces.

If I am specifying what section to repeat via the “(…)” and"\n", Why does this work:
Your code so far


let repeatNum = "42 42 42";
let reRegex = /^(\d+)(\s)\1\2\1$/; // Change this line
let result = reRegex.test(repeatNum);

and not this?

let repeatNum = "42 42 42";
let reRegex = /(\d+)(\s)\1\2\1$/; // Change this line
let result = reRegex.test(repeatNum);

Do I really need the carat at the beginning?
Your browser information:

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

Challenge: Reuse Patterns Using Capture Groups

Link to the challenge:

Because without the start-of-line character (^) there can be anything at the beginning and as long as it ends in a number repeated three times, it will match. So you could have “42 42 42 42” or “hello world 6 6 6”, etc.

1 Like

Gotcha. So it’s a best practices situation, but without it I wouldn’t get the desired result of “42 42 42”. it would have been “42 42 42 42”. Thank You Ariel.

It’s not so much a “best practices” as it is a matter of what you are looking for. Is you goal to make sure that the string is only a number repeated exactly 3 times? Then you need both ^ and $. Can you accept any string that ends with a number repeated 3 times? You only need $. Do you just care that it has a number repeated three times in a row somewhere in there? You want to omit both.

1 Like