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

求验证仅由2个字母和4个数字混合组成的字符串的正则表达式

Solution: Regex to Validate 2 Letters + 4 Digits (Any Order)

Here's a regex that perfectly fits your requirements—it ensures the string is exactly 6 characters long, contains exactly 2 English letters (uppercase or lowercase) and exactly 4 Arabic numerals, with no other characters allowed, in any arrangement:

^(?=(?:[^a-zA-Z]*[a-zA-Z]){2}[^a-zA-Z]*$)(?=(?:[^0-9]*[0-9]){4}[^0-9]*$)[a-zA-Z0-9]{6}$

Breakdown of the Regex Components

Let's break this down to understand how it enforces your rules:

  • ^ and $: Anchors that match the start and end of the string, ensuring we validate the entire input (no extra characters before or after).
  • (?=(?:[^a-zA-Z]*[a-zA-Z]){2}[^a-zA-Z]*$): Positive lookahead to guarantee exactly 2 letters:
    • (?:[^a-zA-Z]*[a-zA-Z]){2}: Matches any sequence of non-letters followed by a letter, repeated exactly 2 times.
    • [^a-zA-Z]*$: Ensures there are no additional letters after those 2.
  • (?=(?:[^0-9]*[0-9]){4}[^0-9]*$): Positive lookahead to guarantee exactly 4 digits:
    • (?:[^0-9]*[0-9]){4}: Matches any sequence of non-digits followed by a digit, repeated exactly 4 times.
    • [^0-9]*$: Ensures there are no additional digits after those 4.
  • [a-zA-Z0-9]{6}: Matches exactly 6 characters that are either letters or digits—when combined with the lookaheads, this guarantees the exact count of 2 letters and 4 digits.

Examples of Valid Matches

  • 11a1a1
  • 1a11a1
  • AB1234
  • 98zY76
  • x9x999

Examples of Invalid Matches

  • 111111 (no letters present)
  • aaa123 (3 letters, 3 digits—wrong counts)
  • a1234 (only 5 characters total)
  • 1a1a1a1 (7 characters total)
  • 1a!1a1 (contains a special character)

Customization Options

  • If you only want to allow lowercase letters, replace all instances of [a-zA-Z] with [a-z].
  • If you only want uppercase letters, use [A-Z] instead.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 09:57:00