Regular expression works on regex101.com, but not on prod

Make sure you always select the right regex engine at regex101.com. See an issue that occurred due to using a JS-only compatible regex with [^] construct in Python.

JS regex – at the time of answering this question – did not support lookbehinds. Now, it becomes more and more adopted after its introduction in ECMAScript 2018. You do not really need it here since you can use capturing groups:

var re = /(?:\s|^)@(\S+)/g; 
var str="s  @vln1\n@vln2\n";
var res = [];
while ((m = re.exec(str)) !== null) {
  res.push(m[1]);
}
console.log(res);

The (?:\s|^)@(\S+) matches a whitespace or the start of string with (?:\s|^), then matches @, and then matches and captures into Group 1 one or more non-whitespace chars with (\S+).

To get the start/end indices, use

var re = /(\s|^)@\S+/g; 
var str="s  @vln1\n@vln2\n";
var pos = [];
while ((m = re.exec(str)) !== null) {
  pos.push([m.index+m[1].length, m.index+m[0].length]);
}
console.log(pos);

BONUS

My regex works at regex101.com, but not in…

Leave a Comment