let repeatNum = "42 42 42";
let reRegex = /(\d+)\s\3/; // Change this line
let result = reRegex.test(repeatNum);
let result2 = repeatNum.match(reRegex);
console.log(result2);
but it does not work.
I get errors:
Your regex should reuse the capture group twice.
Your regex should have two spaces separating the three numbers.
As written, your regex says match the first set of numbers that are followed by a space and followed by the results of the 3rd capture group. So for example, reading from left to right - every capture group you add will provide a new number for your \1, \2 and so on.
A regex like (\w+) \1 (\w+) \2 would match “hi hi hello hello” - hi is capture group #1 and can be used by \1. hello is capture group #2 and can be used by \2
I find regex101.com to be a very useful way to test out these kinda regexes since you can type things in and it will highlight what its found and explain to you why.
it seem like you were trying to use it as quantity{} quantifier, it won’t work in that way, @intricatecloud has already explained. I would like to add to it.
In above example "42 42 42" . you have made a group by () and selected all the digit with one or more quantifier \d+ and followed by white space \s. (\d+)\s. After that you have written \3 , \3 here means 3rd matched but you have selected only one group (\d+) therefore it should be \1.
Ex:
“42 42 42” it can be selected as (\d+)(\s)\1\2\1
As per fcc answer is ^(\d+)\s\1\s\1$, I think question is little misleading, it has never stated that it should start with number and end with number.
Yes, it did mention to match numbers that are repeated only three times in a string, each separated by a space. But my question is why to use ^ $ ? Doesn’t that means the given expression has to start with number and end with number. Correct?
Even if we use (\d+)(\s)\1\2\1 or (\d+)\s\1\s\1. It will match only repeated number.
kindly update me.
you need to match a number that repeats exactly 3 times
if you don’t use anchors you will match also "42 42 42 42" when you shouldn’t. I mean, if you can find a way to not match that without using anchors then you don’t need them, but I don’t know a way
Hmmm… exactly 3 times. My expression (\d+)(\s)\1\2\1 or (\d+)\s\1\s\1 too will only match three time. it won’t match “42 42 42 42” or “42 3 42 42 42”. It was nice to get feedback.