Help with Regex

hi, i need help understanding the regex.
i completed the regex section practice but, definately peeked at the hint and solution after i could not understand it on my own.

I can understand the use of “|” and “&”. like
let wsRegex = /(^\s+)|(\s+$)/;
why isn’t the code working if i use “&” instead of “|”
i.e. last exercise in regex section

Why can’t we specify a regex like this
let reRegex = /^\s$/;

similarly
i can’t understand the capture groups

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

why cant the regex be
let reRegex = /(\d+)\s\3/;
doesn’t this match numbers separated with space occurring 3 times

thanks

why isn’t the code working if i use “&” instead of “|”

You don’t really use “&” in regex. Regular expressions are logical “and” by default. Also, “&” means “and”, “|” means “or”, so they’re not interchangeable anyway.

Why can’t we specify a regex like this
let reRegex = /^\s$/;

You can, that just tests true if the string is a single space. But it doesn’t capture anything. In wsRegex it captures the spaces on the front “^” and on the back “$” of a string.

why cant the regex be
let reRegex = /(\d+)\s\3/;
doesn’t this match numbers separated with space occurring 3 times

No, to match 1 or more digits followed by 3 consecutive spaces would be “/(\d+)\s{3}/”
The “\1” in reRegex refers to capture group 1. So “/^(\d+)\s\1\s\1$/” will capture the first digit and will only test true if the following 2 digits seperated by spaces match the first capture group. Which is why “42 42 42”, will match, but “42 24 32” wont.

I had a difficult time with regex at first, but this site really helped me understand and write regex better: https://rubular.com/