Matt Clark
Matt Clark

Reputation: 28589

Regex for UPC-A type barcodes

Given any user input, how can I validate a UPC-A type barcode using a regular expression?

Considering the following cases:

Input              Expected  Actual
00000000000        (X)       (Y)
000000000000       (Y)       (Y)
0000000000000      (X)       (Y)
90000000000        (X)       (Y)
900000000000       (Y)       (Y)
9000000000000      (X)       (Y)
99999999999        (X)       (X)
999999999999       (X)       (X)
9999999999999      (X)       (X)

I have come up with the following expression, however it does not validate the length of the input, only that it contains a single 0 as required by the spec.

^([1-9]*[0]+[1-9]*)$

How can I adjust this expression such that it will only match the marked cases, taking the overall length of the input into account?

The matched text should be 12 numbers, and must contain at least one zero.

Upvotes: 2

Views: 3189

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521168

You could use a positive lookahead here to assert that at least one zero is present:

^(?=.*0)[0-9]{12}$

Demo

Upvotes: 4

Related Questions