Paula
Paula

Reputation: 77

Regular expresion two or three digits and consequently allow only one or two letters

I'm trying to write a regular expression that, if I write two digits, only allows two letters, but if I write three numbers, only allows one letter

123A --> OK
12AB--> OK
AAAA-> KO
1234--> KO
1AAA-> KO
A111-> KO
123AB --> KO

Thi is the reg I have right now

(\d{2,3})([a-zA-Z]{1,2})?$

that I'm trying in https://regex101.com/

but it allows this: 123AB --> KO

Upvotes: 2

Views: 74

Answers (4)

The fourth bird
The fourth bird

Reputation: 163217

You could use a case insensitive match with /i and:

^\d{2}(?!\d{2}$)[A-Z\d]{2}$
  • ^ Start of string
  • \d{2} Match 2 digits
  • (?!\d{2}$) Assert not 2 digits to the end of the string
  • [A-Z\d]{2} Match 2 chars A-Z or a digit
  • $ End of string

Regex demo

Upvotes: 0

ArtBindu
ArtBindu

Reputation: 1972

Use this regex: ^\d{2,3}[a-zA-Z]{1,2}$

enter image description here

Demo: https://regex101.com/r/l7XjNy/1

Upvotes: 0

anubhava
anubhava

Reputation: 784998

You may use:

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

RegEx Demo

Upvotes: 3

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626738

You can use

^\d{2}(\d[a-zA-Z]|[a-zA-Z]{2})$

See the regex demo.

Details:

  • ^ - start of string
  • \d{2} - two digits
  • (\d[a-zA-Z]|[a-zA-Z]{2}) - a capturing group that matches either a digit and a letter, or two letters
  • $ - end of string.

Upvotes: 3

Related Questions