sscanf高级用法

理解了%[^|]|这个模式就基本能解析复杂字符串了。
这个模式是%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}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值