Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for three letters and four numbers?

I have this regex I am supposed to create that accepts the following formats:

  1. Any 3 letters (case-insensitive, no other characters except for alphabetic characters)
  2. Any 2 letters with a dash in between (case-insensitive)
  3. Any 4 digits

This is what I have come up with so far: ^([a-zA-Z]([a-zA-Z]|-)[a-zA-Z])|[0-9]{4}$

The issue with this regex is that it accepts a combination of 4 letters as well, but I only want three consecutive letters. What do I need to change in my regex to accomplish this?

like image 995
user12149354 Avatar asked Dec 09 '25 12:12

user12149354


1 Answers

You may use:

^(?:[a-zA-Z][a-zA-Z-][a-zA-Z]|[0-9]{4})$

RegEx Demo

RegEx Details:

  • ^: Start
  • (?:: Start non-capture group that match either of these 2 alternatives
    • [a-zA-Z][a-zA-Z-][a-zA-Z]: Match 3 letters or a letter-letter
    • |: OR
    • [0-9]{4}: Match 4 digits
  • ): End non-capture group
  • $: End
like image 98
anubhava Avatar answered Dec 12 '25 05:12

anubhava



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!