RegEx Split () function commit - empty string as first record

run the code to visualize a little the problem I am facing:

  • This is the text to be divided.
:20:0444453880181732
:21:0444453880131350
:22:CANCEL/ABCDEF0131835055
:23:BUY/CALL/E/EUR
:82A:ABCDEFZZ80A
:87A:4444655604
:30:061123
:31G:070416/1000/USNY
:31E:070418
:26F:PRINCIPAL
:32B:EUR1000000,00
:36:1,31000000
:33B:USD1310000,00
:37K:PCT1,60000000
:34P:061127USD16000,00
:57A:ABCDEFZZ80A

This is my regex

 Regex r = new Regex(@"\:\d{2}\w*\:", RegexOptions.Multiline);

 MatchCollection matches = r.Matches(Content);
 string[] items = r.Split(Content);

 // ----- Fix for first entry being empty string.
 int index = items[0] == string.Empty ? 1 : 0;

 foreach (Match match in matches)
 {
    MessageField field = new MessageField();

    field.FieldIdExtended = match.Value;
    field.Content = items[index];

    Fields.Add(field);

    index++;
 }

As you can see from the comments, the problem occurs when splitting a string. It returns an empty string as the first element. Is there an elegant way to solve this problem?

Thanks Dimi

+5
source share
2 answers

The reason you get this behavior is because your first split delimiter has nothing before, and this first record is empty.

The way to resolve this issue is probably to capture the value you want in the regular expression, and then just get it from the set of matches.

, , - :

Regex r = new Regex(@"^:(?<id>\d{2}\w*):(?<content>.*)$", RegexOptions.Multiline);

MatchCollection matches = r.Matches(Content);

foreach (Match match in matches)
{
    MessageField field = new MessageField();

    field.FieldIdExtended = match.Groups["id"].ToString()
    field.Content = match.Groups["content"].ToString();

    Fields.Add(field);

}

. , . 20 id 0444453880181732 . 100% , , , , .:)

, .

+4

:

string[] items = r.Split(Content, StringSplitOptions.RemoveEmptyEntries);

.

-3

All Articles