sscanf/scanf正则用法

%[ ] 的用法: %[ ] 表示要读入一个字符集合 , 如果 [ 后面第一个字符是 ”^” ,则表示反意思。

                     [ ] 内的字符串可以是 1 或更多字符组成。空字符集( %[] )是违反规定的,可

                     导致不可预知的结果。 %[^] 也是违反规定的。 
         

%[a-z] 读取在 a-z 之间的字符串,如果不在此之前则停止,如

              char s[]="hello, my friend” ;         // 注意 : , 逗号在不 a-z 之间

              sscanf( s, “%[a-z]”, string ) ; // string=hello

%[^a-z] 读取不在 a-z 之间的字符串,如果碰到 a-z 之间的字符则停止,如

              char s[]="HELLOkitty” ;         // 注意 : , 逗号在不 a-z 之间

              sscanf( s, “%[^a-z]”, string ) ; // string=HELLO

%*[^=]    前面带 号表示不保存变量。跳过符合条件的字符串。

              char s[]="notepad=1.0.0.1001" ;

       char szfilename [32] = "" ;

       int i = sscanf( s, "%*[^=]", szfilename ) ; // szfilename=NULL, 因为没保存

int i = sscanf( s, "%*[^=]=%s", szfilename ) ; // szfilename=1.0.0.1001

%40c      读取 40 个字符

              The run-time

library does not automatically append a null terminator

to the string, nor does reading 40 characters

automatically terminate the scanf() function. Because the

library uses buffered input, you must press the ENTER key

to terminate the string scan. If you press the ENTER before

        the scanf() reads 40 characters, it is displayed normally,

        and the library continues to prompt for additional input

        until it reads 40 characters

%[^=]     读取字符串直到碰到 ’=’ 号, ’^’ 后面可以带更多字符 , 如:

              char s[]="notepad=1.0.0.1001" ;

       char szfilename [32] = "" ;

       int i = sscanf( s, "%[^=]", szfilename ) ; // szfilename=notepad     

       如果参数格式是: %[^=:] ,那么也可以从 notepad:1.0.0.1001 读取 notepad

             

使用例子:

       char s[]="notepad=1.0.0.1001" ;

char szname [32] = "" ;

char szver [32] = “” ;

sscanf( s, "%[^=]=%s", szname , szver ) ; // szname=notepad, szver=1.0.0.1001

总结: %[] 有很大的功能,但是并不是很常用到,主要因为:

1 、许多系统的 scanf 函数都有漏洞 . ( 典型的就是 TC 在输入浮点型时有时会出错 ).

2 、用法复杂 , 容易出错 .

3 、编译器作语法分析时会很困难 , 从而影响目标代码的质量和执行效率 .

个人觉得第 3 点最致命,越复杂的功能往往执行效率越低下。而一些简单的字符串分析我们可以自已处理。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值