0
:58A:/C/81000098099CL
CBNINGLA
:72:/CODTYPTR/012
/CLEARING/0003
/SGI/DBLNNGLA

am trying to read the swift message above, line :58A: and line :72:, am having a little issue. My code only reads line :58A: like this C/81000098099CL, but I want it to read down the line before getting to line :72:, in short, the output should be like this for line :58A: C/81000098099CL CBNINGLA.

Same also for line :72:, this is because the messages come formatted in this form. This is my code below

if (line.StartsWith(":58A:"))
{
    string[] narr = line.Split('/');
    inflow202.BENEFICIARY_INSTITUTION = narr[2];
}

if (line.StartsWith(":72:"))
{
    inflow202.RECEIVER_INFORMATION = line.Substring(5);
}

2 Answers 2

1

You can replace all new lines not followed by : with spaces (or empty string).

string output = Regex.Replace(text, @"\r?\n(?!:)", " ");
string[] lines = output.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string line in lines)
{
    if (line.StartsWith(":58A:"))
    {
    }
    else if (line.StartsWith(":72:"))
    {
    }
}
2
  • Am pretty new to c# and programming, please can you throw more light on Regex Apr 22, 2014 at 18:08
  • @user3560266 This one is pretty simple. You want to replace newlines with spaces. But if the next line starts with : you don't want to replace the newline. So we are looking for \r\n (newline) not followed by : - (?!:). Also you may have file that uses UNIX newlines - \n, thus we have to make \r optional by appending ?. That gives us \r?. Combining all together it would be \r?\n(?!:) - new line not followed by line starting with :. We replace such match with space. So the text you provided (5 lines) will be converted into text with 2 lines. Then we read line by line. Apr 22, 2014 at 18:30
0

If the message always comes formatted in this form and : never occurs in the text except for these line starters, consider splitting the whole text into an array by : first. On 0th position there will be nothing, on all odd positions will be the number, on all even positions will be the content until next :. This solution will work providing that you are able to read the whole input into a single string first. I.e. having string message, you can do something like:

var splitted = message.Split(':');
for (i=1;i<= splitted.Length -1; i+=2){
   if (splitted[i] == "58A") {
       //do what you need to do, the text you need is stored in splitted[i+1]
   }
   ...
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.