3

Regular expressions with a positive lookbehind anchored to the start doesn't seem to work. Does anybody have an idea why?

For instance the code below returns null.

const str = "foo:25"
const regex = new RegExp(/^(?<=foo:)\d+/);
console.log(regex.exec(str));

Edit: I know how to make it work. I'm asking why this particular regex doesn't match.

gawicks
  • 1,894
  • 15
  • 22
  • Possible duplicate of [Positive look behind in JavaScript regular expression](https://stackoverflow.com/questions/3569104/positive-look-behind-in-javascript-regular-expression) – 31piy Apr 10 '18 at 06:35
  • 1
    Your regex is asking if the string `foo` can be matched *before* the start of the string. This is clearly impossible and therefore only works at Milliways. – Tim Pietzcker Apr 10 '18 at 06:41

2 Answers2

3

The problem with ^(?<=foo:)\d+ pattern is that ^ matches the start of the string and (?<=foo) lookbehind fails the match if there is no foo immediately to the left of the current location - and there is no text before the start of the string.

You could fix it as

const regex = new RegExp(/(?<=^foo:)\d+/);

Here, (?<=^foo:) lookbehind checks for foo at the start of the string, but tests each location in the string since ^ is no longer the part of the consuming pattern.

In JS, for better portability across browsers, you'd better use a capturing group rather than a positive lookbehind (and also, you may directly use the regex literal notation, no need to use /.../ with constructor notation):

var str = "foo:25"
var regex = /^foo:(\d+)/;
console.log(regex.exec(str)[1]);
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
2

The ^ should be before foo. Eg:

const str = "foo:25"
const regex = new RegExp(/(?<=^foo:)\d+/);
console.log(regex.exec(str));
Aniket Sahrawat
  • 12,410
  • 3
  • 41
  • 67