2

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

Community
  • 1
  • 1
Derek
  • 450
  • 5
  • 9

2 Answers2

5

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.

Dean Taylor
  • 40,514
  • 3
  • 31
  • 50
  • Thanks Dean, your suggestion worked like a charm! except for one tiny problem. this exp doesn't seem to check the end of the email for a .com or .org etc.. – Derek Feb 25 '14 at 15:03
  • For actual validation of the email address I would refer you to this question: http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address – Dean Taylor Feb 25 '14 at 17:21
0

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

fejese
  • 4,601
  • 4
  • 29
  • 36