【问题标题】:Regular Expression with exactly 2 uppercase letters and 3 numbers正好有 2 个大写字母和 3 个数字的正则表达式
【发布时间】:2026-01-08 21:05:01
【问题描述】:

我需要匹配包含完全 2 个大写字母和 3 个数字的单词。数字和大写字母可以在单词中的任何位置。

HelLo1aa2s3d: 是的

WindowA1k2j3: 真

AAAsjs21js1: 假

ASaaak12:错误

我的正则表达式尝试,但只匹配 2 个大写字母:

([a-z]*[A-Z]{1}[a-z]*){2}

【问题讨论】:

  • “大写数字”?什么是大写数字?
  • 澄清一下,包含 3 个大写字母或 4 个数字的字符串会被取消资格吗?也就是说,字符串中必须正好有 2 个大写字母和 3 个数字?
  • 是的! >AAAsjs21js1:假

标签: javascript regex


【解决方案1】:

你可以使用正则表达式lookaheads

/^(?=(?:.*[A-Z].*){2})(?!(?:.*[A-Z].*){3,})(?=(?:.*\d.*){3})(?!(?:.*\d.*){4,}).*$/gm

解释:

^                     // assert position at beginning of line
(?=(?:.*[A-Z].*){2})  // positive lookahead to match exactly 2 uppercase letters
(?!(?:.*[A-Z].*){3,}) // negative lookahead to not match if 3 or more uppercase letters
(?=(?:.*\d.*){3})     // positive lookahead to match exactly 3 digits
(?!(?:.*\d.*){4,})    // negative lookahead to not match if 4 or more digits
.*                    // select all of non-newline characters if match
$                     // end of line
/gm                   // flags: "g" - global; "m" - multiline

Regex101

【讨论】:

  • 它们可以在任何位置,不一定是连续的。
  • 啊。谢谢你的收获。固定。
  • 这不符合要求的“完全”部分。
  • 我会修改解决方案。我假设 OP 至少意味着。
【解决方案2】:

使用String.match函数的解决方案:

function checkWord(word) {
    var numbers = word.match(/\d/g), letters = word.match(/[A-Z]/g);

    return (numbers.length === 3 && letters.length === 2) || false;
}

console.log(checkWord("HelLo1aa2s3d"));  // true
console.log(checkWord("WindowA1k2j3"));  // true
console.log(checkWord("AAAsjs21js1"));   // false
console.log(checkWord("ASaaak12"));      // false

【讨论】:

    【解决方案3】:

    我认为,您只需要提前一次。

    ^(?=(?:\D*\d){3}\D*$)(?:[^A-Z]*[A-Z]){2}[^A-Z]*$
    
    • \d 是数字的 short\D\d 的否定,匹配一个非数字
    • (?= 打开一个积极的lookahead(?: 打开non capturing group
    • ^ 开始(?=(?:\D*\d){3}\D*$) 向前看正好三位,直到$ end
    • 如果条件成功,(?:[^A-Z]*[A-Z]){2}[^A-Z]* 匹配一个正好有两个大写字母的字符串,直到$ 结束。 [^ 打开negated character class

    Demo at regex101

    如果您只想允许使用字母数字字符,请将 [^A-Z] 替换为 [a-z\d] like in this demo

    【讨论】:

      【解决方案4】:

      没有前瞻,纯正则表达式:

      http://regexr.com/3ddva

      基本上,只检查每个案例。

      【讨论】:

        最近更新 更多