aslum
aslum

Reputation: 12254

How can I recognize a valid barcode using regex?

I have a barcode of the format 123456########. That is, the first 6 digits are always the same followed by 8 digits. How would I check that a variable matches that format?

Upvotes: 2

Views: 7872

Answers (4)

Greg E.
Greg E.

Reputation: 2742

You haven't specified a language, but regexp. syntax is relatively uniform across implementations, so something like the following should work: 123456\d{8}

  • \d Indicates numeric characters and is typically equivalent to the set [0-9].
  • {8} indicates repetition of the preceding character set precisely eight times.

Depending on how the input is coming in, you may want to anchor the regexp. thusly:

^123456\d{8}$

Where ^ matches the beginning of the line or string and $ matches the end. Alternatively, you may wish to use word boundaries, to ensure that your bar-code strings are properly separated:

\b123456\d{8}\b

Where \b matches the empty string but only at the edges of a word (normally defined as a sequence consisting exclusively of alphanumeric characters plus the underscore, but this can be locale-dependent).

Upvotes: 5

Sam Holder
Sam Holder

Reputation: 32936

123456\d{8}

should do it. This breaks down to:

  • 123456 - the fixed bit, obviously substitute this for what you're fixed bit is, remember to escape and regex special characters in here, although with just numbers you should be fine
  • \d - a digit
  • {8} - the number of times the previous element must be repeated, 8 in this case.

the {8} can take 2 digits if you have a minimum or maximum number in the range so you could do {6,8} if the previous element had to be repeated between 6 and 8 times.

Upvotes: 3

David B
David B

Reputation: 2698

123456\d{8}

123456  # Literals
\d      # Match a digit
  {8}   # 8 times

You can change the {8} to any number of digits depending on how many are after your static ones.

Regexr will let you try out the regex.

Upvotes: 5

Justin Morgan
Justin Morgan

Reputation: 30760

The way you describe it, it's just

^123456[0-9]{8}$

...where you'd replace 123456 with your 6 known digits. I'm using [0-9] instead of \d because I don't know what flavor of regex you're using, and \d allows non-Arabic numerals in some flavors (if that concerns you).

Upvotes: 2

Related Questions