-2

There are segments in the below-mentioned string. Each segment is started with a tilt(~) sign and I want to check if there exists a segment in which the AAA segment appears and on its 3rd index a number 63 is present.

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

I want to do it with a regular expression to avoid lengthy coding. I have tried and come up with this (~AAA) to check if this segment exists or not but because I am new to regular expressions I don't know how to check if 63 appears on the 3rd index or not? If anyone can help I will be very thankful.

Aamerallous
  • 133
  • 13

4 Answers4

2

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.*");
    }
JosephHirn
  • 720
  • 3
  • 9
  • i have done it like above C# code. so i mark it as answer. but actually the reason why i post this question was that i want to do it by the help of regular expression. by using regular expression these 10 line of codes can be converted into 2 or 3 lines. – Aamerallous May 20 '13 at 13:39
0

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

The_Cthulhu_Kid
  • 1,839
  • 1
  • 31
  • 42
0
   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");
Mahdi Tahsildari
  • 13,065
  • 14
  • 55
  • 94
0

You could use this:

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

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

79E09796
  • 2,120
  • 1
  • 20
  • 33