正好包含2个大写字母和3个数字的正则表达式

Regular Expression with exactly 2 uppercase letters and 3 numbers

本文关键字:3个 数字 正则表达式 大写字母 包含 2个      更新时间:2023-09-26

我需要匹配包含两个大写字母和三个数字的单词。数字和大写字母可以在单词的任何位置。

HelLo1aa2sd:真正的

WindowA1k2j3:真正的

AAAsjs21js1:错误

ASaaak12:错误

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

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

您可以使用regexlookaheads:

/^(?=(?:.*[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

我认为,您只需要一个前瞻。

^(?=(?:'D*'d){3}'D*$)(?:[^A-Z]*[A-Z]){2}[^A-Z]*$
  • 'd是数字的缩写。'D'd的否定,并且匹配非数字
  • (?=开启了积极的前瞻。(?:打开一个非捕获组
  • ^开始时,(?=(?:'D*'d){3}'D*$)向前看正好三个数字,直到$结束
  • 如果条件成功,则(?:[^A-Z]*[A-Z]){2}[^A-Z]*匹配正好具有两个上字母的字符串,直到$结束。[^打开一个否定的字符类

在regex101 上演示

如果您想只允许使用字母数字字符,请像本演示中那样用[a-z'd]替换[^A-Z]

使用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

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

http://regexr.com/3ddva

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