Trying to reuse a pattern but it's failing

Hi,

The below is my solution for the last challenge on Regex:

let hello = "   Hello, World!  ";
let wsRegex = /[\w,!]+\s[\w,!]+/;
let wsRegex1 = /Hello, World!/;
let result = hello.match(wsRegex)[0];

However I wanted to reuse the pattern as below but it’s failing to match:

let hello = "   Hello, World!  ";
let wsRegex = /([\w,!])+\s\1+/;
let wsRegex1 = /Hello, World!/;
let result = hello.match(wsRegex)[0];

Can anyone please shed any light as to why it’s failing?

Many thanks.

Fraser

([\w,!])+

one or more word characters or commas or exclamation marks, followed by

\s

…a single space character, followed by…

\1+

…one or more of the character 1

Hi,

When you say:

are you referring to the digit 1, or the first capture group? I’ve laid my code out as specified on the capture group exercise as follows:

let repeatRegex = /(\w+)\s\1/;

The only difference with my code is that I’m including additional non-alphanumeric characters enclosed in brackets… unless I’m missing something very obvious.

Thanks.

Ah crap. I forgot about backreferences, sorry, ignore what I said. Anyway, the + modifier isn’t inside the capturing group parentheses

1 Like

When you write the above regex, the \1 means whatever was captured by \w+ will also need to be after the space character (\s). So if the characters captured by the capture group is the string Hello,, then in order to match, part of the string would need to be Hello, Hello,, which is obviously not the case here.

Yep that makes sense… I had forgotten it wasn’t just a shorthand technique and that the subsequent matches need to match like for like in the string.

Many thanks.

No problem, thanks for coming back to me