user25911
user25911

Reputation: 21

How to extract required data?

The serial data I receive is like this

AT+CMGR=3

+CMGR: "REC READ","919742400000",,"2014/01/17 22:52:44+22"  
G LED ON

OK

Actually it will be like this

AT+CMGR=3\r\n\r\n+CMGR: "REC READ","919742400000",,"2014/01/17 22:52:44+22"\r\nG LED ON\r\n\r\n\r\nOK\r\n

I need to extract

3 (Message Index can have any integer value)

REC READ (Msg Status)

919742400000 (Originating Number)

2014/01/17 22:52:44+22 (Date Time Stamp)

G LED ON (Actual Message SMS)

The VC#.Net code that I have written is

Regex r = new Regex(@"\+CMGR: (\d+),""(.+)"",""(.+)"",(.*),""(.+)""\r\n(.+)\r\n");
Match m = r.Match(mySMS); //mySMS is a string and contains the above mentioned data


int Index = int.Parse(m.Groups[1].Value);   //(3 in above example)
string Status = m.Groups[2].Value;      //(REC READ)
string Sender = m.Groups[3].Value;      //(919742400000)
string Sent = m.Groups[4].Value;        //2014/01/17 22:52:44+22
string Message = m.Groups[5].Value;     //G LED ON

Another thing is The actual message (SMS) can contain double quoted strings like

"G "LED" ON" and I might also be able to extract

G "LED" ON

The above VC# code is not working.

How can I use RegEx or any other method to extract the required datas?

Upvotes: 1

Views: 306

Answers (1)

Henk Holterman
Henk Holterman

Reputation: 273274

I would say your main structure is line-based, ie you either use ReadLine() oryou split the string:

string[] lines = mySMS.Split(new string[] {"\r\n"}, StringSplitOptions.None);

Now lines[2] constians your main data, comma-separated. lines[3] is your G "LED" ON.

To parse lines[2]:

string[] parts = lines[2].Split(',');
string OriginatingNumber = parts[1];
string DateTimeStamp = parts[3];

parts[0] will hold +CMGR: "REC READ", use another Split() or break on the : some other way.

Upvotes: 3

Related Questions