Regexes and quantifiers

Can someone please clarify a few questions about quantifiers to me?

let test = “angel”;
let myRegex = /e?le?/;
let result = text.match(myRegex);

This matches " el ". I know that " ? " returns the preceding item 0 or 1 times but the process is not clear to me as the regex contains 2 " e " characters, while the test variable holds only one " e ". How does JS handle this?

1 let test = “Testpw1aa”;
2 let myRegex = /a?/;
3 let result = text.match(myRegex);

Why no match is found, while “aa” is matched if I use the global flag?

Thanks in advance to anyone who’ll be willing to help out =)

it is true that the variable holds only one e, but remeber that the regex says 0 or 1 e, so the regex is 0 or 1 e, followed by l, followed by zero or one e
the only part of the string that matches is “el” as there is one e followed by one l, followed by 0 e

this is a thing that may seem weird, but remember you are matching "0 or 1 a", so the regex starts checking the beginning of the string. Does it found something that match the pattern? yes, there are 0 a, so it returns [""]
if you use the global flag it returns all the matches of the string, so ["","","","","","","","a","a",""]

the definition of the ? is “Matches between zero and one times, as many times as possible, giving back as needed (greedy)”

each colored part is a match, if you count them it correspond:
Online regex tester and debugger- PHP- PCRE- Python- Golang and JavaScript 13-2-2020 12-54-56
this is from the website https://regex101.com/ , if you want to test it remember to select ECMAScript (JavaScript) on the left

1 Like

Now this was extremely helpful. Thank you so much!

Oh, by the way I am using the regex101 tool, but I wasn’t able to get over my doubts with the mere use of it.