理解了%[^|]|
这个模式就基本能解析复杂字符串了。
这个模式是%s
的一个正则表达式方向的进化,本意也是要取字符串,但是是有选择的取。如何选择,就写在[]
中。其中的^
表示“不取”,不取哪些模式就写在^
的后面。
例子中的[^|]
就表示不取|
,取到|
就停止了,最后一个|
则对应源串中的|
。
整体来看,%[^|]|
就表示取到|
为止(不取这个|
)然后跳过|
。
另外还有更多的取%s的进化,比如%[0-9]
(只取数字)、%[0-9a-z]
(取数字或者小写英文字符)、%[0-9.]
(取数字或者英文句号)。
注意:这种正则表达式的进化只存在于%s的选取,对于%d之类的其他类型不需要。因为这些其他类型只要遇到不符合的字符就会立即停止,%s则可以包含各种字符,所以才需要正则表达式来指导它取哪些不取哪些。
如下面例子中的ip字段的选取,直接用%d即可。(当然后面还要写上
|
来跳过源串中的|
)
例子:
#include <stdlib.h>
#include <stdio.h>
#include <debug_macro/my_debug.h>
int main()
{
char type[32] = {0};
char ip[17] = {0};
int port = 0;
char jsonStr[128] = {0};
char *string = "cAgent|10.10.10.1|1234|{Json}";
sscanf(string, "%[^|]", type);
DEBUG_PRINTF("type: %s\n", type);
sscanf(string, "%[^|]|%[^|]", type, ip);
DEBUG_PRINTF("type: %s, ip: %s\n", type, ip);
sscanf(string, "%[^|]|%[^|]|%d", type, ip, &port);//注意这个port的选取,直接写%d即可
DEBUG_PRINTF("type: %s, ip: %s, port: %d\n", type, ip, port);
sscanf(string, "%[^|]|%[^|]|%d|%s", type, ip, &port, jsonStr);
DEBUG_PRINTF("type: %s, ip: %s, port: %d, jsonStr: %s\n", type, ip, port, jsonStr);
return 0;
}
运行结果:
[root@localhost195-46 other]# gcc test.c -o test -I ./ -DMY_DEBUG_ON
[root@localhost195-46 other]# ./test
[main:16]type: cAgent
[main:18]type: cAgent, ip: 10.10.10.1
[main:20]type: cAgent, ip: 10.10.10.1, port: 1234
[main:22]type: cAgent, ip: 10.10.10.1, port: 1234, jsonStr: {Json}