I need to match words that contains exactly 2 uppercase letters and 3 numbers. Numbers and uppercase letters can be at any positions in the word.
HelLo1aa2s3d: true
WindowA1k2j3: true
AAAsjs21js1: false
ASaaak12: false
My regex attempt, but only matches exactly 2 uppercase letters:
([a-z]*[A-Z]{1}[a-z]*){2}
I need to match words that contains exactly 2 uppercase letters and 3 numbers. Numbers and uppercase letters can be at any positions in the word.
HelLo1aa2s3d: true
WindowA1k2j3: true
AAAsjs21js1: false
ASaaak12: false
My regex attempt, but only matches exactly 2 uppercase letters:
([a-z]*[A-Z]{1}[a-z]*){2}
Share
Improve this question
edited May 15, 2016 at 11:57
timolawl
5,56415 silver badges29 bronze badges
asked May 15, 2016 at 11:01
Davit AvetisyanDavit Avetisyan
1291 silver badge9 bronze badges
4
- 1 "uppercase numbers"? What is an uppercase number? – Edvaldo Silva de Almeida Jr Commented May 15, 2016 at 11:04
- To clarify, a string with 3 uppercase letters or 4 numbers would disqualify? That is, there must be exactly 2 uppercase letters and exactly 3 numbers in the string? – timolawl Commented May 15, 2016 at 11:15
- yes! >AAAsjs21js1: false – Davit Avetisyan Commented May 15, 2016 at 11:16
- Bobble Bubble's solution is correct. – Wiktor Stribiżew Commented Oct 20, 2017 at 9:10
4 Answers
Reset to default 4You 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
Regex101
The solution using String.match
function:
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
is the negation of\d
and matches a non-digit(?=
opens a positive lookahead.(?:
opens a non capturing group.- At
^
start(?=(?:\D*\d){3}\D*$)
looks ahead for exactly three digits until$
the end. - If the condition succeeds
(?:[^A-Z]*[A-Z]){2}[^A-Z]*
matches a string with exactly two upper alphas until$
end.[^
opens a negated character class.
Demo at regex101
If you want to allow only alphanumeric characters, replace [^A-Z]
with [a-z\d]
like in this demo.
Without lookahead, pure regex:
http://regexr./3ddva
Basically, just checks every case.