You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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:

Modified Regex to Exclude Special-Character-Only Local Parts

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., test in test.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.com
  • user_123+tag@domain.co.uk
  • my-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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 04:32:22