I have a regex that doesn't work on my website, but whenever I tried to use it on jsfiddle it works. My goal was to get the URLs existing in a sentence.
const regex = /\b(?:(?:https?\:\/\/|\b)(?:(?:\d{1,3}\.){3}\d{1,3}|(?<![\@\.])(?:[^\s\/\?\#\@\.]+\.){1,2}[a-z]{2,3})(?:[\/\#\:\?][^\s\@]*|\b)(?![\@\.]))/gm;
Here is the error that I'm getting:
SyntaxError: Invalid regular expression: /\b(?:(?:https?\:\/\/|\b)(?:(?:\d{1,3}\.){3}\d{1,3}|(?<![\@\.])(?:[^\s\/\?\#\@\.]+\.){1,2}[a-z]{2,3})(?:[\/\#\:\?][^\s\@]*|\b)(?![\@\.]))/: Invalid group
Use the "best regex trick ever", consume emails first, then capture your pattern matches.
Here is a way to extract the URLs:
const regex = /\S+@\S+|\b((?:https?:\/\/)?(?:(?:\d{1,3}\.){3}\d{1,3}|(?:[^\s\/?#@.]+\.){1,2}[a-z]{2,3})(?:[\/#:?][^\s@]*|\b))(?![@.])/g;
let result = [], m;
const text = "Visit http://lalala.la or contact lala@lalala.la";
while(m=regex.exec(text)) {
if (m[1] !== undefined) result.push(m[1]);
}
console.log(result);
See the regex demo.
The \S+@\S+| part matches one or more non-whitespace chars, @ and again one or more non-whitespace chars, so the rest of the pattern can match in any other context. The code only returns Group 1 matches if any (note the capturing parentheses around the second alternative).