您的位置:首页 > 其它

sscanf/scanf正则用法

2011-07-16 23:02 204 查看
%[ ] 的用法: %[ ] 表示要读入一个字符集合 , 如果 [ 后面第一个字符是 ”^” ,则表示反意思。
[ ] 内的字符串可以是 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 点最致命,越复杂的功能往往执行效率越低下。而一些简单的字符串分析我们可以自已处理。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: