Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RegEx non-capturing group issue

Why following return ["vddv"] instead of ["dd"]:

"aaavddv".match(/(?:v).*(?:v)/)
like image 428
Handsome Nerd Avatar asked Dec 28 '22 00:12

Handsome Nerd


2 Answers

(?:v) # matches 'v' this is a non-capturing group, not a lookbehind
.*    # matches 'dd'
(?:v) # matches 'v' this is a non-capturing group, not a lookahead

Non-capturing groups still participate in the match. Perhaps you want a lookahead/behind? But Javascript does not support lookbehind.

like image 85
alan Avatar answered Dec 29 '22 14:12

alan


"aaavddv".match(/(?:v)(.*)(?:v)/)[1]

the whole match is correctly vddv but if you want to match only dd you need to use a capturing group (and look at element [1])

like image 21
Fabrizio Calderan Avatar answered Dec 29 '22 13:12

Fabrizio Calderan