JS RegEx - lookaheads

How does this regex
/^\D(?=\w{5,})(?=\w*\d\d+)/
match this string
"astr1on11aut" ?

doesn’t string have to end with a digit, because of \d+?

there is not an anchor to match the end of string ($)

Hello there.

Something to realise is that it is not matching the whole word. Essentially, you are matching everything before the lookahead - in this case a.

Why?
^ - Asserts to match the start of the string
\D - any non digit (matches a)
(?=\w{5,}) - Before matching the a, make sure there are 5 or more word characters (there are str1on11aut)
(?=\w*\d\d+) - Before matching the a, make sure there are 0 or more word characters followed by 2 or more digits (there are n11)

All that is matched is the first letter. In order for it to be matched, (5 word characters) and (one word character with two digits) had to be found.

Hope this helps

1 Like

This is great explanation! It did help me and clarified my misunderstanding.
I know understand lookaheads better.