問題描述
將電子郵件地址與地址標籤匹配的正則表達式 (regex that matches email addresses with address tags)
Possible Duplicate: Is there a php library for email address validation? How to validate an email in php5?
I am aware that there have been plenty of questions regarding email address regular expressions. My question has a specific requirement that I have been unable to find the answer to.
I need a regex that matches email addressas and allows for address tags, such as "testing+tags@gmail.com". Most regexes I have found fail on email addresses that contain a tag.
NOTE please do not point me to this link. I am looking for something practical, not perfect
EDIT I am aware of the existence of built‑in validation in most web app frameworks. RoR, PHP, Django, etc all have it built in. Sometimes, though, for whatever reason, there is a special need. Maybe the user can't use validation. maybe they are writing their app in some obscure language that doesn't have built‑in validation functions, or has them, but they are out of date. In that case, a regular expression is still useful
‑‑‑‑‑
參考解法
方法 1:
You could should use filter_var to validate email instead
var_dump(filter_var('bob@example.com', FILTER_VALIDATE_EMAIL));
Example for your case:
echo filter_var('bob+long@example.com', FILTER_VALIDATE_EMAIL) !== false? 'Valid': 'Invalid';
方法 2:
My personal favorite has always been this:
/\A[\w+\‑.]+@[a‑z\d\‑.]+\.[a‑z]+\z/i
Another popular one is also
/\b[A‑Z0‑9._%+‑]+@[A‑Z0‑9.‑]+\.[A‑Z]{2,4}\b/
If you are doing this in PHP and if feasible for your problem, I would suggest using filter_var
as otherwise suggested. This is merely a suggestion should you need a regular expression that is practical and understood to be imperfect.