[英]Regular Expression with exactly 2 uppercase letters and 3 numbers
I need to match words that contains exactly 2 uppercase letters and 3 numbers.我需要匹配正好包含2大写字母和3个数字的话。 Numbers and uppercase letters can be at any positions in the word.
数字和大写字母可以位于单词中的任何位置。
HelLo1aa2s3d: true
HelLo1aa2s3d:真
WindowA1k2j3: true
WindowA1k2j3:真
AAAsjs21js1: false
AAAsjs21js1:假
ASaaak12: false
ASAaak12:假
My regex attempt, but only matches exactly 2 uppercase letters:我的正则表达式尝试,但只匹配 2 个大写字母:
([a-z]*[A-Z]{1}[a-z]*){2}
You can use regex lookaheads :您可以使用正则表达式前瞻:
/^(?=(?:.*[A-Z].*){2})(?!(?:.*[A-Z].*){3,})(?=(?:.*\d.*){3})(?!(?:.*\d.*){4,}).*$/gm
Explanation:解释:
^ // 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
The solution using String.match
function:使用
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
I think, you need just one lookahead.我认为,你只需要一个前瞻。
^(?=(?:\D*\d){3}\D*$)(?:[^A-Z]*[A-Z]){2}[^A-Z]*$
\\d
is a short for digit. \\d
是数字的缩写。 \\D
is the negation of \\d
and matches a non-digit \\D
是\\d
的否定并且匹配一个非数字(?=
opens a positive lookahead . (?:
opens a non capturing group . (?=
打开一个积极的前瞻。 (?:
打开一个非捕获组。^
start (?=(?:\\D*\\d){3}\\D*$)
looks ahead for exactly three digits until $
the end .^
start (?=(?:\\D*\\d){3}\\D*$)
向前看正好三位数字,直到$
the end 。(?:[^AZ]*[AZ]){2}[^AZ]*
matches a string with exactly two upper alphas until $
end.(?:[^AZ]*[AZ]){2}[^AZ]*
匹配一个正好有两个大写字母的字符串,直到$
结束。 [^
opens a negated character class . [^
打开一个否定字符类。 Demo at regex101在 regex101 上演示
If you want to allow only alphanumeric characters, replace [^AZ]
with [az\\d]
like in this demo .如果您只想允许使用字母数字字符,请将
[^AZ]
替换为[az\\d]
就像在本演示中一样。
http://regexr.com/3ddva http://regexr.com/3ddva
Basically, just checks every case.基本上,只检查每个案例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.