简体   繁体   中英

Check whether a string is composed of 3 capital letters and 4 numbers

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?

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".

I imagine something like this would work: https://regex101.com/r/81ZTVQ/1

^[AZ]{3}[0-9]{4}$

Explanation:

  • [AZ] - 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 predicate

Test 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

^(?=(.*[AZ]){3})(?=(.*\\d){4})([AZ\\d]{7})$

Explanation

  • (?=(.*[AZ]){3}) - Positive lookahead that matches AZ with any preceding character, 3 times.
  • (?=(.*\\d){4}) - Positive lookahead that matches 0-9 with any preceding character, 3 times.
  • ([AZ\\d]{7}) - the argument provided must match this predicate - 7 of any combination of AZ and 0-9. I just prefer having it in a group, hence the grouping.

Working logically backwards, we can have any combination of AZ 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

Another regex: ^[AZ]{3}\\d{4}$

  • \\d stands for digits
  • ^ anchor before first char
  • $ anchor after last char

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[A-Z]\d{3}$)|(^[A-Z]{2}\d{2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"not a match"));
    }

Output:

ABC1234 is a match
1A2B3C4 is a match
ABCD123 is not a match
aBC1234 is not a match
ABC12345 is not a match

  • (...) represents a group
  • ^ represents the beginning of a string
  • [AZ] represents a capital letter
  • [AZ]{n} represents n capital letters
  • \\d represents a digit
  • $ represents the end of a string
  • | is used to indicate that whatever is to the right or left is acceptable

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM