Tobias Golbs
Tobias Golbs

Reputation: 4616

RegEx to validate Number

i try to validate a number with a simple scheme but i am not that good in Regular Expressions.

The number has this format:

XXXXXXX-XX-X where X is a number between 0 and 9.

I tried the following: /[0-9]{6}\-[0-9]{2]\-[0-9]{1}/ but it does not validate.

Do you see what i have done wrong?

Upvotes: 2

Views: 1246

Answers (1)

p.s.w.g
p.s.w.g

Reputation: 149088

You've got a typo in your pattern. The third ] should be a }:

/[0-9]{6}\-[0-9]{2}\-[0-9]{1}/

You can simplify this further though. You don't need to escape a - outside of a character class, and you don't need a quantifier for {1}:

/[0-9]{6}-[0-9]{2}-[0-9]/

Depending on what regular expression engine you're using, you could probably substitute \d for [0-9]. In JavaScript they are equivalent, however, in many engines, they are slightly different. \d is intended for use with Unicode digits, rather than decimal digits (e.g. it might match Easter Arabic digits). If this is acceptable, you can use:

/\d{6}-\d\d-\d/

Also, if you need to prohibit any leading or trailing characters, you might consider adding start (^) and end ($) anchors around your pattern:

/^[0-9]{6}-[0-9]{2}-[0-9]$/

Or

/^\d{6}-\d\d-\d$/

Upvotes: 5

Related Questions