Derek
Derek

Reputation: 480

Regex invalid group error while using in javascript

I have the following regex that checks for multiple types of email address inputs

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

I got this off How do I regex a name and an email out of the 3 major email clients in ruby?

The problem i am facing is that while using this in javascript i get an error "Uncaught SyntaxError: Invalid regular expression: /[\W"]*(?"<name>".*?)[\"]*?\s*[<(]?(?"<email>"\S+@[^\s>)]+)[>)]?/: Invalid group "

I spent an entire day trying to fix this and i found out that the problem has something to do with lookbehind That javascript doesn't support

I'm very bad at regex expressions and need some advice. Can someone please point me in the right direction.

PS: I am trying to make this function to integrate it with jquery validate plugin

Jquery Validation

Upvotes: 2

Views: 4559

Answers (2)

Dean Taylor
Dean Taylor

Reputation: 42021

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.

Upvotes: 5

fejese
fejese

Reputation: 4628

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

Upvotes: 0

Related Questions