Anatol
Anatol

Reputation: 2033

Limit regex to exactly three characters

My regex looks like this:

^[1-3][\/\][1-3]+$|-

It allows 1/3, 2/3, 2/- so far so good. Unfortunately 3/3/3 is also valid. I tried to limit it like this:

^[1-3][\/\][1-3]{0,2}$|-

which does not work as expected.

How can I allow only three characters where first and last can either be a number from 1 to 3 or - and the second has to be a slash?

Edit I wrote the wrong range it´s not 1-9 but 1-3

Upvotes: 0

Views: 82

Answers (4)

Mojtaba Rezaeian
Mojtaba Rezaeian

Reputation: 8736

This may be what you are looking for: (Numbers from 1 to 3 and minus acceptable in first and third location with a "/" between them)

^[1-3-]\/[1-3-]$

DEMO

Upvotes: 0

karthik manchala
karthik manchala

Reputation: 13640

You can use the following:

^[1-9]\/[1-9-]$

See DEMO

Upvotes: 0

Kasravnd
Kasravnd

Reputation: 107287

I think ^[1-9-]/[1-9-]$ is what you want!

DEMO

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

You can use [0-9-] to match "a number from 1 to 9, or '-'". The overall expression would look like this:

^[0-9-][\/][0-9-]$

Demo.

Note that the dash is placed at the end of the character class. This is important, because a dash in the middle is interpreted as a character range.

Upvotes: 0

Related Questions