Reputation: 1918
I need to check if a string is composed by 3 capital letters and 4 digits.
For example: ABC1234
How do I check it using regular expressions?
Upvotes: 0
Views: 1700
Reputation: 857
I imagine something like this would work: https://regex101.com/r/81ZTVQ/1
^[A-Z]{3}[0-9]{4}$
Explanation:
[A-Z]
- Case sensitive sequential character (capital A to capital Z) match predicate {n}
- exact number match of preceding match predicate [0-9]
numeric range (in this case, 0 to 9) match predicateTest cases:
ABC1234 - Full match
A1BC234 - No match
GFQ9230 - Full match
ACB0000 - Full match
Edit:
I'd like to include my addition that is somewhat similar to Rawling's answer, yet slightly different.
https://regex101.com/r/81ZTVQ/7
^(?=(.*[A-Z]){3})(?=(.*\d){4})([A-Z\d]{7})$
Explanation
(?=(.*[A-Z]){3})
- Positive lookahead that matches A-Z with any preceding character, 3 times.(?=(.*\d){4})
- Positive lookahead that matches 0-9 with any preceding character, 3 times.([A-Z\d]{7})
- the argument provided must match this predicate - 7 of any combination of A-Z and 0-9. I just prefer having it in a group, hence the grouping.Working logically backwards, we can have any combination of A-Z and 0-9 as long as the length is 7. Then our positive lookaheads assert the length of the requirements (in this case, 4 digits, 3 capital letters).
Test Cases for Edit
ABC1234
A1BC234
GFQ9230
ACB0000
AGF1923
A237323
3E44E4E
12344AB
AAAE123
AK348A3
Upvotes: 3
Reputation: 4488
Another regex: ^[A-Z]{3}\d{4}$
\d
stands for digits^
anchor before first char$
anchor after last charUpvotes: 1
Reputation: 50114
If you're looking for any order, here are two interesting ways of doing it:
^(?=(.*\d){4})(?=(.*[A-Z]){3}).{7}$
"Exactly seven characters, containing 4 digits and 3 capitals".
^(?<d>){4}(?<c>){3}((?<-d>\d)|(?<-c>[A-Z])){7}$
"Expect 4 digits and 3 capitals; then ensure we have exactly 7 digits-or-capitals in total, counting each as we go".
Upvotes: 4
Reputation: 542
You can check if a string is composed of 3 capital letters and 4 numbers (assuming those capital letters and numbers can appear anywhere in the string) like this:
Regex rgx = new Regex(@"(^[A-Z]{3}\d{4}$)|(^[A-Z]{2}\d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