Regex邮箱验证优化:排除仅含特殊字符的无效邮箱
Alright, let's fix this regex to filter out those pesky email addresses where the local part (before the @) is nothing but special characters. Here's how to do it properly:
First, here's the adjusted regex that meets your requirement:
^(?=.+[a-zA-Z0-9])[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$
Breakdown of the Changes
The critical addition here is the positive lookahead at the start: (?=.+[a-zA-Z0-9]). This rule ensures the local part contains at least one letter or number—so it can't be made up entirely of underscores, plus signs, or other allowed special symbols.
Let's break down the entire regex piece by piece:
^: Anchors the match to the start of the string(?=.+[a-zA-Z0-9]): Positive lookahead that verifies there's at least one alphanumeric character somewhere in the local part[a-zA-Z0-9!#$%&'*+/=?^_{|}~-]+`: Allowed characters for the local part (includes alphanumerics and all standard email special characters), requiring at least one character@: Matches the mandatory@separator[a-zA-Z0-9-]+: Matches the main domain part (e.g.,testintest.com)(?:\.[a-zA-Z0-9-]+)*: Matches optional subdomains or top-level domains (e.g.,.co.uk), using a non-capturing group to avoid unnecessary grouping$: Anchors the match to the end of the string
Test Cases
Valid Emails That Will Match
john.doe@example.comuser_123+tag@domain.co.ukmy-email@test.org
Invalid Emails That Will Be Excluded
_@test.com(only underscore in local part)____@test.com(multiple underscores, no alphanumerics)+_@test.com(mixed special characters, no alphanumerics)!#$%@domain.com(only special symbols)
Notes
If you need to support additional edge cases (like periods in the local part, which are allowed but can't be at the start/end or consecutive), you can adjust the local part logic. For example, a version allowing properly placed periods would look like:
^(?=.+[a-zA-Z0-9])[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$
The core lookahead rule stays the same—its job is still to filter out any local part that's 100% special characters.
内容的提问来源于stack exchange,提问作者Ziko

