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

正则表达式优化求助:限制特殊字符匹配问题修正

Fixing Your Password Validation Regex

Got it, let's get this regex sorted so it properly blocks restricted characters while keeping all your required rules intact. The main problem with your current pattern is that the final .{8,40} matches literally any character (except newlines)—that’s why stuff like @ or accented letters are still passing. We need to replace that wildcard with an explicit list of allowed characters.

Here’s the revised regex, formatted for readability using the x flag (which lets us add comments and line breaks without breaking functionality):

/^
  (?=.*\d)                # Require at least one digit
  (?=.*[a-z])             # Require at least one lowercase letter
  (?=.*[A-Z])             # Require at least one uppercase letter
  (?!.*\s)                # Block any whitespace characters
  [a-zA-Z0-9$*%!.,^]{8,40}# Only allow these characters, 8-40 total length
$/x

What Changed & Why:

  • Replaced .{8,40} with [a-zA-Z0-9$*%!.,^]{8,40}: This explicitly limits every character in the string to only the allowed set (letters, digits, and your approved special characters: $*%!.,^). No more random symbols slipping through!
  • Added ^ and $ anchors: These make sure we validate the entire string from start to finish—no partial matches slipping by (a good practice for full-string validation like passwords).
  • Used the x flag: This is just for readability. It lets us split the regex into lines with comments so anyone looking at it later can quickly understand each rule without parsing a messy single line.

Testing With Your Examples:

Should Pass:

  • abcABC123 → All allowed characters, hits every required rule
  • aaBB33!! → Includes allowed special characters, valid length
  • !a*Bc9!.abBC*4 → Mix of specials, letters, digits, perfect length

Should Fail:

  • abc ABC 123 → Has whitespace (caught by the (?!.*\s) check)
  • abc@ABC?123 → Uses restricted characters @ and ?
  • áááBBB333 → Accented letters aren’t in our allowed set

Fallback for Environments Without x Flag:

If you’re using this in a system that doesn’t support the x flag (some older regex engines), you can collapse it into a single line without comments—it works exactly the same:

/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?!.*\s)[a-zA-Z0-9$*%!.,^]{8,40}$/

内容的提问来源于stack exchange,提问作者Nick

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 16:47:53