Alex
Alex

Reputation: 10216

What is a better regular expression/ regex than my pattern for testing a house number?

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-"

Upvotes: 2

Views: 202

Answers (1)

falsetru
falsetru

Reputation: 369054

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

Upvotes: 2

Related Questions