Skip to content Skip to sidebar Skip to footer

Regex Invalid Group Error While Using In Javascript

I have the following regex that checks for multiple types of email address inputs [\W']*(?.*?)[\']*?\s*[<(]?(?\S+@[^\s>)]+)[>)]? I got this off H

Solution 1:

JavaScript in browsers generally do not support named capture.

Named capture bits are these (?<name>.*?) and (?<email>\S+@[^\s>)]+).

You can replace named capture with numbered capture groups, changing this:

[\W"]*(?<name>.*?)[\"]*?\s*[<(]?(?<email>\S+@[^\s>)]+)[>)]?

to this:

[\W"]*(.*?)[\"]*?\s*[<(]?(\S+@[^\s>)]+)[>)]?

Regular expression visualization

So in JavaScript it would look like this:

match = subject.match(/[\W"]*(.*?)[\"]*?\s*[<(]?(\S+@[^\s>)]+)[>)]?/i);
if (match != null) {
    // matched text: match[0]
    // match start: match.index
    // capturing group 1 (name): match[1]
    // capturing group 2 (email): match[2]
} else {
    // Match attempt failed
}

Remember that capture groups might only be added if they capture something.


Solution 2:

There's no lookbehind as far as I can tell (it'd be something like this: (?<=prefix)) But maybe the labeled matching is not supported ((?"<name>"...)). Try without that and reference the matches by their number:

/[\W"]*(.*?)[\"]*?\s*[<(]?(\S+@[^\s>)]+)[>)]?/

The name will be the first and the email is the second captured group


Post a Comment for "Regex Invalid Group Error While Using In Javascript"