David Hume
David Hume

Reputation: 77

Regex for a combination of alphanumeric characters and range of numbers

I need a regex for PORT input, it must allow only inputs like this:

gei_1/8 or xgei-0/7/0/5

-It must allow underscore and hyphen only at the start: gei_1 or xgei-0

-Then it must allow two digit numbers within a range of 0-48, separated by forward slash with no spaces between them. No more than three numbers: /7/0/48

-It cannot allow forward slash or anything at the end

Right now, I have the following Regex for the alphanumeric part: /^[A-Za-z][A-Za-z0-9]*(?:_[A-Za-z0-9]+)*$/

For the number part I have: ^(\d|1\d|2\d|3\d|4[0-8])\/(\d|1\d|2\d|3\d|4[0-8])\/(\d|1\d|2\d|3\d|4[0-8])$

Thanks for the help

Upvotes: 1

Views: 698

Answers (1)

The fourth bird
The fourth bird

Reputation: 163632

To repeat the forward slash 1 - 3 times you could use a range to match 0-48 and repeat that 1-3 times using a quantifier {1,3}

(?:\/(?:[0-9]|[1-3][0-9]|4[0-8])){1,3}

The full pattern could look like

^[A-Za-z][A-Za-z0-9]*[_-][A-Za-z0-9]+(?:\/(?:[0-9]|[1-3][0-9]|4[0-8])){1,3}$

Regex demo

Upvotes: 1

Related Questions