Reputation: 12254
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
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
Reputation: 32936
123456\d{8}
should do it. This breaks down to:
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
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
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