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

寻求符合特定规则的JS正则表达式(正则经验不足)

Hey there! I've crafted a regex that satisfies all 6 of your specified rules, plus explanations to help you understand each part:

^([a-z]{1,12}|[0-9][a-z]{0,11}|[a-z]{0,11}[0-9])$

Key Note:

Make sure to use the case-insensitive flag (usually denoted as i in most regex engines—like JavaScript, Python, or regex testers) so a and A are treated as identical.


How This Regex Works:

It's split into three valid patterns (separated by |, meaning "OR") to cover all allowed scenarios:

  1. All letters (1-12 characters): [a-z]{1,12}

    • Matches any combination of letters (case-insensitive) with length from 1 to 12. This covers inputs like name, John, ALICE.
  2. Single digit at the start, plus 0-11 letters: [0-9][a-z]{0,11}

    • Ensures the digit is only at the beginning of the word. The total length is capped at 12 (1 digit + up to 11 letters). Valid examples here are 3name, 5, 9Smith.
  3. 0-11 letters followed by a single digit: [a-z]{0,11}[0-9]

    • Ensures the digit is only at the end. Again, total length maxes out at 12 (up to 11 letters + 1 digit). This covers inputs like name1, X4, Jane7.

Checking Against Your Rules:

Let's confirm each requirement is met:

  • ✅ Ignore case: Handled by the i flag.
  • ✅ Allow but not mandatory numbers: The first pattern has no digits, while the other two have exactly one.
  • ✅ Only one digit max: None of the patterns allow more than one digit.
  • ✅ Digit not in middle: Digits are restricted to either the start or end of the word.
  • ✅ Max length 12 characters: All patterns cap at 12 total characters; there's no minimum length (since you can have just a single letter or digit).
  • ✅ No special characters: Only letters and digits are allowed in the character classes, so any special symbols (like #, $, %) will be rejected.

Edge Cases Covered:

  • Single-character inputs: a, Z, 5 are all valid.
  • Exactly 12 characters: abcdefghijkl (all letters), 1abcdefghijk (digit + 11 letters), abcdefghijk2 (11 letters + digit) are accepted—anything longer gets rejected.
  • Invalid inputs like na3me (digit in middle) or name11 (two digits) are correctly rejected.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 19:32:34