sscanf与正则表达式(c—version)

本文通过多个示例展示了如何使用C语言中的sscanf函数进行字符串解析,包括跳过数字、匹配特定字符范围及提取指定格式的信息等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

学习代码:

#include<stdio.h>

void test01();//squeeze numbers
void text02();//squeeze numbers
void test03();//print front[] words
void test04();//match words_1stVersion
void test05();//match words_2stVersion
void test06();//match ^[x1-x2]
void test07();//cut string out using its format
void test08();//take the useful information string
void test09();//practice

int main()
{
    test01();
    test02();
    test03();
    test04();
    test05();
    test06();
    test07();
    test08();
    test09();


    return 0;
}

void test01()
{
    char *ch = "123hello";
    char buf[1024];

    sscanf(ch,"%*d%s", buf);
    printf("1%s",buf);

}

void test02()
{
    char *ch = "hello123";//or add \t or space between o and 1, but not suggested!
    char buf[1024];

    sscanf(ch, "%*[a-z]%s", buf);
    printf("2%s", buf);
}

void test03()
{
    char *ch = "123hello";
    char buf[1024];

    sscanf(ch,"%6s", buf);
    printf("3%s", buf);
}

void test04()
{
    char *ch = "123abcdecccfg";
    char buf[1024];

    sscanf(ch,"%*d%[a-c]", buf);
    printf("4%s", buf);
}

void test05()
{
    char *ch = "aa22bbccdefg123";
    char buf[1024] = {0};

    sscanf(ch, "%[abc]", buf);//if it is not match successfully, then just stop matching
    printf("5%s", buf);
}

void test06()
{
    char *ch = "123abcdefg";
    char buf[1024];

    sscanf(ch,"%[^a-z]", buf);
    printf("6%s", buf);
}

void test07()
{
    char *ch = "219.231.164.200";
    int a, b, c, d;

    a = b = c = d = 0;
    sscanf(ch, "%d.%d.%d.%d", &a, &b, &c, &d);
    printf("7%d %d %d %d", a, b, c, d);
}

void test08()
{
    char *ch = "12345#liuwenhan$1114068569";//take my name
    char buf[1024];

    sscanf(ch,"%*[^#]#%[^$]", buf);
    printf("8%s", buf);
}

void test09()
{
    char *ch = "Helloworld@itcast.cn";
    char buf1[1024];
    char buf2[1024];

    sscanf(ch,"%[^@]", buf1);
    sscanf(ch, "%*[^@]@%s", buf2);
    printf("9%s\n%s", buf1, buf2);
}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值