Why is this working?

I don’t understand why the code below does work on freecodecamp and returns true while on other websites (like regexr) it doesn’t work! (not the first time)
/^(\d+)\s\1\s\1$/ (Use capture groups in reRegex to match numbers that are repeated only three times in a string, each separated by a space.
(my attempt was : /(\d+)\s\1\s\1/ and it wrote : Your regex should not match "42 42 42 42" . Can someone explain it further for me? How can this be done?)
Thanks! :blush:

I can’t speak to how other regex checkers are behaving. If you show us specifically what you mean, we might be able to explain it.

Do you understand why your pattern /(\d+)\s\1\s\1/ didn’t work?

1 Like

Nope I don’t think I do.

If a string contains the regular expression pattern, you will get a match. Because “42 42 42 42” contains the same number three times, it will match. However, the requirement is to only match if the string is exactly the same number three times. By adding the beginning and end anchors, you have changed your pattern to “The beginning of the string, a number, space, the same number, space, the same number, the end of string”. “42 42 42 42” does not contain this pattern, because there is an extra " 42" in there.

1 Like

Ohhhh, yeah I do understand it now! That was great, thank you! Okay another question if you don’t mind it, this is the prompt : Write a regex and use the appropriate string methods to remove whitespace at the beginning and end of strings.
(the string : Hello, World! )
My answer: /(^\s+)(.+)(\s.$)/g
result = hello.replace(wsRegex, “$2”)
It worked. But I don’t understand the solution given by freecodecamp : /^\s+|\s+$/g
Isn’t | supposed to be like ‘or’, why does it match both spaces?

Because it will replace every piece of the string that matches the pattern. Any group of one or more whitespaces that is either at the start of the string or at the end of the string will be replaced.

1 Like