5

I'm having trouble fully understanding this Python 2 regular expression to validate email addresses. I found a great example here.

r"[^@]+@[^@]+\.[^@]+"

So according to regex101 this means we need atleast 1 value before the '@' symbol, 1 '@' symbol, and any number of characters after the '@' symbol and atleast 1 '.' symbol. First of all correct me if I'm wrong, but secondly no documentation anywhere explains what "[^@]" means. So I'm having trouble understanding what the above code means.

All I would like to do is convert the above code to Javascript but have only found help with the following case:

/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/

This means very little to me, but have found this useful example here. The problem is that the JavaScript expression over checks.

For example, the following string passes in Python but fails the JS expression:

hi@gmail.com.edu/org

It really comes down to 1 question. How can I correct the JavaScript regex to match that of the Python regex?

Max
  • 2,072
  • 5
  • 26
  • 42
  • 1
    `[^@]` => [Negated character class](http://www.regular-expressions.info/charclass.html). Not `@` – Tushar Oct 25 '16 at 04:12
  • 1
    No need to change anything in regex, [use it as it is](https://regex101.com/r/PEfZAx/1). And, maybe add anchors. – Tushar Oct 25 '16 at 04:14
  • Hi @Tushar the python regex is correct, it is the javascript I'm worried about. – Max Oct 25 '16 at 04:16
  • 2
    The python regex can be used as is in JavaScript: `/[^@]+@[^@]+\.[^@]+/` – 4castle Oct 25 '16 at 04:20
  • wow. stupid me, I was unaware that the regex transferred so well. @4castle please submit your solution so I can mark as correct. – Max Oct 25 '16 at 04:27
  • @Tushar ahh yes. I didn't originally realize that that was submitted in JS. Please submit your solution below. What anchors would be necessary? – Max Oct 25 '16 at 04:29

1 Answers1

10

Simply convert python regex to Javascript.

Python: r"[^@]+@[^@]+\.[^@]+"

Javascript: /[^@]+@[^@]+\.[^@]+/

Max
  • 2,072
  • 5
  • 26
  • 42