A regular expression for numbers and only one hyphen in the middle

I am trying to write a regular expression to allow numbers and only one hypen in the middle (cannot be at the beginning or at the end) for example, pattern: 02-04 , 02 valid, but pattern: -- or - or -02 or 04- or 02-04-06 not acceptable

I tried something like this, but it would allow - at the beginning and also allow a few -

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

I am not so familiar with regex, so a little explanation will be really helpful.

EDIT: Sorry to repeat this again, but I need the numbers to be only 2 digits (123-346), considered invalid.

+7
source share
3 answers

Try the following:

 /^\d{1,2}(-\d{1,2})?$/ 

One or two digits followed by optional (hyphen followed by one or two digits)

+12
source

Pretty easy:

 ^\d+(-\d+)?$ 

At least one digit ( + ) ( \d ), followed by an optional group containing a hyphen minus ( - ), followed by at least one digit.

+5
source

For strings containing only this pattern, the following should work

 ^(\d{2}-)?\d{2}$ 

A 2-digit group followed by a minus ending in a 2-digit group without a minus.

+2
source

All Articles