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.
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.*");
}