Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex with repeated characters and length in .NET

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
like image 400
Mike Flynn Avatar asked Nov 30 '25 23:11

Mike Flynn


1 Answers

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

like image 109
Allan Avatar answered Dec 03 '25 15:12

Allan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!