Skip to content Skip to sidebar Skip to footer

Is It Possible To Match The Start Of The Remainder Of A /g Javascript Regex?

I am building a parsing state machine which uses some light regex to detect certain tokens. I want to be able to look at an arbitrary position in a large string and determine if a

Solution 1:

The sticky (y) flag does exactly that and recently made it into the JavaScript standard (it was originally a Mozilla extension):

> var digit = /\d/y;
> digit.exec('12x3')
[ '1', index: 0, input: '12x3' ]
> digit.exec('12x3')
[ '2', index: 1, input: '12x3' ]
> digit.exec('12x3')
null

If you’re targeting an engine without support, you can use the index property of the match and make sure it lines up with the previous value of the regular expression’s lastIndex:

functionstickyMatch(regex, string) {
    var expectedIndex = regex.lastIndex;
    var match = regex.exec(string);

    if (!match || match.index !== expectedIndex) {
        regex.lastIndex = 0;
        returnnull;
    }

    return match;
}

var digit = /\d/g;

console.log(stickyMatch(digit, '12x3'));
console.log(stickyMatch(digit, '12x3'));
console.log(stickyMatch(digit, '12x3'));

(Slicing repeatedly likely won’t be slow on modern engines thanks to string optimizations¹, but this is nicer anyway.)

¹ *waves hands vigorously*

Post a Comment for "Is It Possible To Match The Start Of The Remainder Of A /g Javascript Regex?"