1

So I have this string which I want to serialize as a GS1 Data Matrix:

var code = (01)09501101020917(17)190508(10)ABCD1234(410)9501101020917

According to the Guidelines this isn't valid, because the Application Identifier (10) has a variable length so I need a (ascii code 29) separator at the end of that section (so something like this
"(10)ABCD1234{(char) 29}"

So I split my input string into parts, one part the Application Identifier (AI) and the other part being the data.

My Regex and code for getting the AIs:

var identifierRegex = new Regex(@"\([0-9]{2,}\)", RegexOptions.ExplicitCapture);
var identifiers = identifierRegex.Split(code);

This returns me almost the correct result, identifiers is a string[] containing 5 elements, the first one being empty and the rest are correct.

My Regex and code for getting the AIs and the data:

var dataRegex = new Regex(@"\([0-9]{2,}\)[0-9A-z]{0,}", RegexOptions.ExplicitCapture);
var aisAndData = dataRegex.Split(code);

This returns me the completely wrong results, aisAndData is a string[] with 5 empty elements

Here is a link to regexstorm.net showing the expected results of the first Regex. And Here is a link to regexstorm.net showing the expected result of the second Regex

What am I missing/ what am I doing wrong for my code not to work?

MindSwipe
  • 4,416
  • 15
  • 30
  • If you have *matching* patterns, why use `Regex.Split`? Use `Regex.Matches`. Note `A-z` must be `A-Za-z`. `var identifiers = identifierRegex.Matches(code).Cast().Select(x => x.Value)`. – Wiktor Stribiżew Feb 22 '19 at 08:03
  • Sorry if I'm misunderstanding you @WiktorStribiżew as I'm pretty new to Regex. I'm trying to get all the parts of my original string (`code`) that match my Regex, for example I want to get `{(01), (17), (10), (410)}` from my identifier Regex – MindSwipe Feb 22 '19 at 08:06
  • Exactly, why use `Split` if you need to match? – Wiktor Stribiżew Feb 22 '19 at 08:07
  • @WiktorStribiżew What else should I use? The Regex.Split documentation makes it pretty clear this is what I want to use stating that the Regex.Split Method "Splits an input string into an array of substrings at the positions defined by a regular expression match" – MindSwipe Feb 22 '19 at 08:09
  • Because `splitting` means *removing text you match with the regex pattern and returning only the text that was not matched* – Wiktor Stribiżew Feb 22 '19 at 08:11
  • @WiktorStribiżew thanks, I see I misunderstood the documentation and the multiple SO questions about it – MindSwipe Feb 22 '19 at 08:14

0 Answers0