Question

I have the below mentioned string.

ISA*ABC**TODAY*ALEXANDER GONZALEZ~HL*CDD*DKKD*S~EB*1*AKDK**DDJKJ~AAA*Y**50*P~AAA*N**50*P~AAA*N**63*C~AAA*N**50*D~AAA*N**45*D

In the above string there are segments.Each segment is started with tilt(~) sign and i want to check if there exist a segment in which AAA segment appears and on it's 3rd index a number 63 is present. I need a regular expression for this.i have tried and come up with this (~AAA) but since i am new to regular expression i don't know how to check if 63 appears on the 3rd index or not? If any one can help i will be very thankful.

Was it helpful?

Solution

I have to agree with Sebastian's comment. This can be accomplished using simple Split operations.

    private static bool Check(string input)
    {
        int count = 0;
        foreach (string segment in input.Split('~'))
        {
            string[] tokens = segment.Split('*');
            if (tokens[0] == "AAA")
            {
                count++;
                if (count == 3)
                {
                    if (tokens[3] == "63") return true;
                    else return false;
                }
            }
        }
        return false;
    }

EDIT: Since you want fewer lines of codes, how about LINQ?

    private bool Check(string input)
    {
        return input.Split('~').Select(x => x.Split('*')).Any(x => x.Length >= 4 && x[0].Equals("AAA") && x[3].Equals("63"));
    }

EDIT2: For completeness, here's a Regex solution as well:

    private bool Check(string input)
    {
        return Regex.IsMatch(input, @".*~AAA\*([^\*~]*\*){2}63.*");
    }

OTHER TIPS

There are many, many, sites and tools that can help you with regex. Google can help you further.

You could use this:

~AAA\*[A-Z]\*\*63

Note the \ is used to escape the * and [A-Z] matches any uppercase alphabetical character.

   string s = "ISA*ABC**TODAY*ALEXANDER GONZALEZ~HL*CDD*DKKD*S~EB*1*AKDK**DDJKJ~AAA*Y**50*P~AAA*N**50*P~AAA*N**63*C~AAA*N**50*D~AAA*N*   *45*D";
   string[] parts = s.Split('~');
   for (int i = 0; i < parts.Count(); i++)
   {
      MessageBox.Show("part "+i.ToString()+" contains 63: "+parts[i].Contains("63").ToString());
   }

this is just an example. you can do a lot more, I checked existance of 63 in any segment.
so if you exactly want to check if segment 3 the code would be:

bool segment3Contains63 = s.Slplit('~')[3].Contains("63");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top