Search code examples
javascriptregexlookbehind

Regex : Using an anchor with positive lookbehind


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.


Solution

  • 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]);