Reputation: 77
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
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 stringUpvotes: 0
Reputation: 1972
Use this regex:
^\d{2,3}[a-zA-Z]{1,2}$
Demo: https://regex101.com/r/l7XjNy/1
Upvotes: 0
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