-1

Look at this regexp:

console.log(/^a(?=b)$/.test('ab'));

I have tried it on an online tool. This tool says my 'ab' string matches. But it displays false in javascript.

Any idea ?

Thanks

Bob5421
  • 6,002
  • 10
  • 44
  • 120
  • [It does not match anywhere](https://regex101.com/r/vX1GrJ/1). You can't expect any text after the end of string. It is just the same as `$a` like regexps. – Wiktor Stribiżew Mar 03 '20 at 09:04

1 Answers1

1

A lookahead does not consume anything, so the $ won't match because there's still the b left.
You can see it if you omit the $:

console.log(/^a(?=b)/.test('ab'));

In more detail you ask your engine the following questions:

  1. Does my expression start at the beginning of the string (^)? - Yes it does.
  2. Is there an a coming? - Yes there is.
  3. Is immediately after the a a b lurking around the corner? - Yes there is.
  4. Is this the end of the string? - No it's not, the b is still round the corner, my poor boy!

So the engine cannot report a match and is left crying on the floor because her behaviour was called strange in the first place where she made everything correct.

Jan
  • 38,539
  • 8
  • 41
  • 69