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

求助:编写符合指定规则的密码验证正则表达式

Hey there! Great job putting together that regex for password validation—let me break it down for you so you understand exactly how it works, and confirm that it does meet all your requirements, including rule #4.

Let's Break Down Your Regex Step by Step

Your regex (?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[$@#&!]).{6,12} uses positive lookaheads—these are the (?=...) parts—to check each of your password rules before validating the length. Here's what each piece does:

  • (?=.*\d): This lookahead scans the entire string to make sure there’s at least one digit (\d is shorthand for [0-9]). The .* means "any character (except newlines) zero or more times," so it lets the regex look past any characters to find a digit somewhere in the password.
  • (?=.*[a-z]): Similarly, this checks that there’s at least one lowercase letter from a to z.
  • (?=.*[A-Z]): This ensures the password includes at least one uppercase letter from A to Z.
  • (?=.*[$@#&!]): This is exactly what you need for rule #4! It verifies that the password has at least one of your specified special characters: $, @, #, &, or !. Characters inside a regex character set ([]) don’t need escaping (unless they’re special to the set, like ^, -, or ]—none of which are in your list), so this part is written correctly.
  • .{6,12}: Finally, this checks that the entire password is between 6 and 12 characters long. The . matches any single character, and {6,12} specifies that this character (or any combination of characters) must appear 6 to 12 times total.
Does This Regex Meet All Your Rules?

Absolutely! Let’s verify each requirement:

  1. ✅ At least one lowercase letter: Covered by (?=.*[a-z])
  2. ✅ At least one uppercase letter: Covered by (?=.*[A-Z])
  3. ✅ At least one digit: Covered by (?=.*\d)
  4. ✅ At least one special character from [$@#&!]: Covered by (?=.*[$@#&!])
  5. ✅ Length 6-12 characters: Covered by .{6,12}
Quick Test Examples
  • Valid passwords: Pass12! (checks all boxes), aB3$xyz (7 characters, includes all required types)
  • Invalid passwords: pass12! (missing uppercase), PASS12! (missing lowercase), PassWord! (missing digit), Pass123 (missing special character), Pass12!3456789 (13 characters, too long)

A quick note: If you ever need to add or remove special characters, just update the [$@#&!] set—for example, to add %, change it to [$@#&!%].

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:46:13