I have a regex where I need to match the letter part in a capture. The letters can be 1-3 characters in length and must be the same letter. No ABC, but A, AA, or AAA works, followed by a number. I can only match A1 currently, not AA1. I am using .NET for the Regex.
^(?<pool>([A-Z])\1{0,2})(?<number>(100)|[1-9]\d?)$
A1
AA2
AAA3
B5
CC7
Would the following regex work for you?
\b(([A-Z])\2{0,2}(?:100|[1-9]\d?))\b
DEMO
It does accept: A1 AA2 AAA3 B5 CC7 and does not match AAAA4 or ABC123
If you want to use Named Capturing Groups and Backreferences to them then you can change your regex into:
^(?<pool>([A-Z]))\k<pool>{0,2}(?<number>(100|[1-9]\d?))$
DEMO
Let me know if it works for you, also have a look at:
https://www.regular-expressions.info/named.html
Last but not least, if you want the named capturing group <pool> to match and capture A, AA or AAA you can use:
^(?<pool>([A-Z])\2{0,2})(?<number>(100|[1-9]\d?))$
DEMO
With only named Capturing Groups:
^(?<pool>(?<letter>[A-Z])\k<letter>{0,2})(?<number>(100|[1-9]\d?))$
DEMO
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With