Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS - Positive Look Ahead & End Of Line

Why is the first test failing?

/^[ab](?=[cd])$/.test('ac') // => false

/^[ab](?=[cd])/.test('ac')  // => true

Only the string 'ac', 'ad', 'bc' & 'bd' should pass.

No other strings like 'ac bd' or 'acbd'.

However, using the $ isn't helping in the 1st regex, whereas the 2nd one will also pass for strings like 'acbd'.

like image 687
Ankur Avatar asked Jun 02 '15 09:06

Ankur


2 Answers

You need to understand how look-aheads work.

The (?=[cd])$ positive look-ahead checks if the following characters match the pattern that follows the look-ahead (in your case, the end of string). The end of string is not c nor d. Thus, there is no match.

You need to put the $ to the look-ahead to make it match a:

^[ab](?=[cd]$)

See demo on Regex101.com

Regular expression visualization

Debuggex Demo

like image 178
Wiktor Stribiżew Avatar answered Sep 23 '22 12:09

Wiktor Stribiżew


This regex should pass:

/^[ab](?=[cd]$)/.test('ac') 

Reason why

/^[ab](?=[cd])$/.test('ac') 

is failing because $ (end of input) is not there after a or b (there is a letter c after a).

like image 22
anubhava Avatar answered Sep 22 '22 12:09

anubhava