7

I am trying to write a regular expression to allow numbers and only one hypen in the middle (cannot be at start or at the end) say pattern: 02-04 , 02are acceptable but pattern: -- or - or -02 or 04- or 02-04-06 are unacceptable

I tried something like this but this would allow - at the beginning and also allow multiple -

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

I am not that good with regex so a little explanation would be real helpful.

EDIT: Sorry to bug you again with this but I need the numbers to be of only 2 digits (123-346) should be considered invalid.

ro ko
  • 2,906
  • 3
  • 37
  • 58

3 Answers3

14

Try this one:

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

One or two digits, followed by, optionally, ( a hyphen followed by one or two digits)

Oussama Jilal
  • 7,669
  • 2
  • 30
  • 53
  • 1
    Same answer as mine, but you beat me to it. So I added an explanation, upvoted, and deleted my own. – slim Aug 23 '12 at 10:47
  • Sorry to bug you again with this but I need the numbers to be of only 2 digits (123-346) should be considered invalid. – ro ko Aug 23 '12 at 10:52
  • 1
    2 digits exactly? Or 1-2 digits? `\d[2]` or `\d\d` matches two digits. `\d[1-2]` or `\d\d?` matches 1 or 2 digits. – slim Aug 23 '12 at 10:54
  • I updated the unswer so it only support one or two digits ({1,2} instead of +) (and thank you @slim) – Oussama Jilal Aug 23 '12 at 11:01
  • @Yasmat and you spotted my [] vs {} fail :) – slim Aug 23 '12 at 12:29
5

Fairly easy:

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

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

Joey
  • 344,408
  • 85
  • 689
  • 683
  • but this would render `02` invalid, as a hyphen is required by your expression – Andreas Wong Aug 23 '12 at 10:43
  • Ah, sorry; overlooked the part that said that the hyphen-minus is optional. Fixed now. That requirement is a bit hard to see in the question, admittedly, as every verbal explanation of the pattern sounds like the hyphen-minus is required. – Joey Aug 23 '12 at 10:46
2

For strings containing only that pattern the following should work

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

A group of 2 digits followed by minus ending with a group of 2 digits without minus.

Gabber
  • 5,152
  • 6
  • 35
  • 49