Using regular expressions to decode an FMD barcode

Viewed 284

I am currently trying to break down a 2D barcode using a regular expression for FMD checks on pharmaceutical products within a c# system. The barcode used in a data matrix barcode.

I am new to regular expressions and have had no experience of using them but have been given a snippet to go off.

The problem I am having is that the details of the barcode can be in any order in the following format:

  • 01 = GTIN Number (fixed 14 digit number)
  • 10 = Batch number (variable length up to 20 characters, or delimited with x1d)
  • 17 = expiry date (fixed 6 digit YYMMDD)
  • 21 = serial number (variable length up to 20 characters, or delimited with x1d)

In the perfect world we would get these in this order but that is not always the case.

We can use the following regular expression when in the order stated above:

01(\d{14})10([a-zA-Z0-9]{1,20})(\\x1d)?17(\d{6})21([a-zA-Z0-9]{1,20})(\\x1d)?

For example; https://regex101.com/r/e5cpla/1

However when trying in any order, I cannot seem to get the expression to recognise the values within. I have tried the following and I am not getting the expected results.

(?=.*01(\d{14}))(?=.*10([a-zA-Z0-9]{1,20}))(?=.*(\\x1d)?)(?=.*17(\d{6}))(?=.*21([a-zA-Z0-9]{1,20}))(?=.*(\\x1d)?).*$

Does anybody have any ideas how we can do this?

1 Answers

You were mighty close to the finish line!

(?:01(\d{14})|10([a-zA-Z0-9]{1,20})(\\x1d)?|17(\d{6})|21([a-zA-Z0-9]{1,20})(\\x1d)?)

Just simply adding a non capturing group around your expression and separating all of your capture groups by | we get an expression that will net your results in any order!

There is one caveat here though: because the non capture group captures one of the elements at a time, only one capture group within it will contain any data and the others will be empty, so you must write a couple of lines of code to account for that.

Here's your example updated, you can see what I mean about the empty capture groups in your substitution. But if you process each match separately and only look at the capture group that has captured something you'll be fine!

https://regex101.com/r/e5cpla/2

Let me know if you have any trouble with this.

Related