Regular Expression Works on Regex101. Com, but Not on Prod

(?:(?<=\s)|^)@(\S+) <-- the problem in positive lookbehind

Working like this on prod: (?:\s|^)@(\S+), but I need a correct start index (without space).

Here is in JS:

var regex = new RegExp(/(?:(?<=\s)|^)@(\S+)/g);

Error parsing regular expression: Invalid regular expression: /(?:(?<=\s)|^)@(\S+)/

What am I doing wrong?

UPDATE

Ok, no lookbehind in JS :(

But anyways, I need a regex to get the proper start and end index of my match. Without leading space.

7

1 Answer

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...

9

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sarah Jenkins

Sarah Jenkins

Senior Technology Editor & AI Specialist

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.

Share this article
Twitter Facebook Pinterest