2

I want to allow the following pattern: either any number or two numbers with a hyphen between them, so basically a house number.

This works so far but seems a little weird to me: /^(\d)+$|^([\d]+-[\d]+)$/g

This correctly valids "1", "12", "12-13" and unvalids "-2" and "12-"

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
Alex
  • 9,911
  • 5
  • 33
  • 52
  • 2
    Watch out for `\d` as this might not do what you expect! It may stand for any digit character and not just arabic (1, 2, 3, ...). See http://stackoverflow.com/questions/6479423/does-d-in-regex-mean-a-digit – Dio F Jan 14 '14 at 14:47
  • My house number is 56b. You're not going to get a match for me. – Spudley Jan 14 '14 at 14:56
  • yes i will, we have a seperate field for that :) you'd have the field house number and additional adress – Alex Jan 14 '14 at 15:02

1 Answers1

2

How about following?

/^\d+(-\d+)?$/
  • You don't need to specify g flag.
  • ? makes following -\d+ part optional.

Example:

/^\d+(-\d+)?$/.test('1')     //    true
/^\d+(-\d+)?$/.test('12')    //    true
/^\d+(-\d+)?$/.test('12-13') //    true
/^\d+(-\d+)?$/.test('-13')   //    false
/^\d+(-\d+)?$/.test('13-')   //    false
falsetru
  • 357,413
  • 63
  • 732
  • 636
  • thanks very much. i now the ? operator but didnt quite made it to a working expression. will accept as soon as timer has expired ;) – Alex Jan 14 '14 at 14:45
  • Try replacing \d with [0-9]. Will work the exact same except will only match numbers 0 through 9, as \d will match numbers but also other digit characters such as eastern Arabic numerals. – Srb1313711 Jan 14 '14 at 14:51
  • Won't non-capturing group be of help here? `/^\d+(?:-\d+)?$/`? – thefourtheye Jan 14 '14 at 14:52
  • @thefourtheye, It depends on what OP want. If what OP want is just check whether the given string match or not, non-capturing group is redundant in my opinion. – falsetru Jan 14 '14 at 14:54
  • @falsetru Oh, I thought non-capturing would be efficient in this case. – thefourtheye Jan 14 '14 at 14:55
  • non-capturing means i would not have the () available as $1 ? – Alex Jan 14 '14 at 15:03