正则表达式读取包含\ n

时间:2016-03-22 18:52:19

标签: c# regex sms

尊重所有人,我一直在阅读在其消息字符串中有\n的短信

string __msg = "+CMGR: \"REC UNREAD\",\"+923001234567\",,,\"16/03/19,15:00:47+20\"\r\nRollNo: 1212\nName: Student\nAddress: Foo bar\r\n\r\nOK\r\n"

我试图在C#

中使用以下正则表达式在组中阅读它
Regex r = new Regex(@"\+CMGR: ""(.+)"",""(.+)"",(.*),""(.+)""\r\n(.+)\r\n");  
Match m = r.Match(__msg);

但它总是在比赛中返回false

请建议我需要更改以在消息字符串中使用\ n读取短信。感谢。

1 个答案:

答案 0 :(得分:0)

您可以将.+替换为[^"]+以提高效果并允许字段内的换行符,并确保匹配所有CR + LF:

\+CMGR:\s*"([^"]+)","([^"]+)",([^"]*),"([^"]+)"[\r\n]+(.+)[\r\n]+

请参阅regex demo,以下是C# code demo

string __msg = "+CMGR: \"REC \nUNREAD\",\"+923001234567\",,,\"16/03/19,15:00:47+20\"\r\nRollNo: 1212\nName: Student\nAddress: Foo bar\r\n\r\nOK\r\n";
Regex r = new Regex(@"\+CMGR:\s*""([^""]+)"",""([^""]+)"",([^""]*),""([^""]+)""[\r\n]+(.+)[\r\n]+");  
Match m = r.Match(__msg);            // And now, just the demo
Console.WriteLine("Val: " + m.Value);
Console.WriteLine("Grp1: " + m.Groups[1].Value);
Console.WriteLine("Grp2: " + m.Groups[2].Value);
Console.WriteLine("Grp3: " + m.Groups[3].Value);
Console.WriteLine("Grp4: " + m.Groups[4].Value);