C# regex struggling

string text = "AT + CMGL =\"REC UNREAD\"\r\r\n+CMGL: 5,\"REC UNREAD\",\"+420733505479\",\"\",\"2015/09/08 13:38:31+08\"\r\nPrdel\r\n\r\nOK\r\n";
Regex regex = new REgex(CMGL:\s(.*?),\\"(.*?)\\",\\"(.*?)\\",\\"\\",\\"(.*?)\\"\\r\\n(.*?)\\r\\n\\r\\n);

I need output like this:

  1. [38-39] 5

  2. [42-52] REC UNREAD

  3. [57-70] +420733505479
  4. [80-102] 2015/09/08 13:38:31+08
  5. [108-113] Prdel

I tried this expression on https://regex101.com and it seems all right but when I run my program, regex fails to find the text. I was only able to force it to find:

+CMGL: 5,

"REC UNREAD",

"+420733505479",

"",

"2015/09/08 13:38:31+08"

Prdel

I have absolutely no idea how this could happen. Could anyone help me please?

Upvotes: 1

Views: 170

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626870

You can use the following regex:

CMGL: (?<num>\d+),"(?<rec>[^"]*)","(?<phone>[^"]*)","[^"]*","(?<date>[^"]*)"\s*(?<badword>.+)

See demo at the .NET-compliant regex tester

Results:

enter image description here

C#:

string text2 = "AT + CMGL =\"REC UNREAD\"\r\r\n+CMGL: 5,\"REC UNREAD\",\"+420733505479\",\"\",\"2015/09/08 13:38:31+08\"\r\nPrdel\r\n\r\nOK\r\n";
Regex regex2 = new Regex(@"CMGL: (?<num>\d+),""(?<rec>[^""]*)"",""(?<phone>[^""]*)"",""[^""]*"",""(?<date>[^""]*)""\s*(?<badword>.+)");
Match match2 = regex2.Match(text2);
if (match2.Success)
{
     Console.WriteLine(match2.Groups["num"].Value);
     Console.WriteLine(match2.Groups["rec"].Value);
     Console.WriteLine(match2.Groups["phone"].Value);
     Console.WriteLine(match2.Groups["date"].Value);
     Console.WriteLine(match2.Groups["badword"].Value);
 }

Upvotes: 2

Related Questions