sscanf 提取AT命令返回结果中的有效数据
C语言 | 如何使用 sscanf 提取AT命令返回结果中的有效数据 - 云+社区 - 腾讯云 (tencent.com)
正则表达式提取不定长字符
AT命令返回结果为:
1 +CWLAP:(4,"TP-LINK_PocketAP_DFBCD4",-57,"38:83:45:df:bc:d4",6) 2 +CWLAP:(3,"LSTM",-61,"8c:21:0a:bc:8e:70",13) 3 +CWLAP:(3,"LabWiFi",-62,"68:3b:78:8f:16:23",1) 4 +CWLAP:(0,"GuestWiFi",-64,"68:3b:78:8f:16:22",1) 5 6 OK
先找到+CWLAP
:
1 strstr(buffer+offset, "+CWLAP:");
使用sscanf+正则表达式提取ssid、mac、rssi:
1 sscanf(str+strlen("+CWLAP:"), "(%d,\"%[^\"]\",%d,\"%[^\"]\",", &ecn, ssid, &rssi, mac);
读取之后,将str指针移动到该行结束,进行下一轮的查找:
1 while (*str++ != '\n') { 2 offset++; 3 }
sscanf函数用法详解
测试
1 #include <stdio.h> 2 #include <string.h> 3 #include <iostream> 4 char* str = 5 "+CWLAP:(4,\"TP-LINK_PocketAP_DFBCD4\",-57,\"38:83:45:df:bc:d4\",6)\r\n\ 6 +CWLAP:(3,\"LSTM\",-61,\"8c:21:0a:bc:8e:70\",13)\r\n\ 7 +CWLAP:(3,\"LabWiFi\",-62,\"68:3b:78:8f:16:23\",1)\r\n\ 8 +CWLAP:(0,\"GuestWiFi\",-64,\"68:3b:78:8f:16:22\",1)\r\n\ 9 \r\n\ 10 OK\r\n"; 11 12 int ecn; 13 char ssid[32]; 14 int rssi; 15 char mac[32]; 16 int channel; 17 char* ptr = NULL; 18 int offset = 0; 19 int main() 20 { 21 while(1){ 22 ptr = strstr(str+offset,"+CWLAP"); 23 if(!ptr)break; 24 sscanf(ptr,"+CWLAP:(%d,\"%[^\"]\",%d,\"%[^\"]\",%d",&ecn, ssid, &rssi, mac,&channel); 25 printf(" ecn = %d\r\n ssid =%s\r\n rssi =%d\r\n mac =%s\r\n channel = %d\r\n",ecn, ssid, rssi, mac,channel); 26 printf("==========================\r\n"); 27 while (*ptr++ != '\n') 28 { 29 offset++; 30 } 31 } 32 system("pause"); 33 return 0; 34 35 }