参考:
今天看到一个程序中sscanf() 的用法,比较有效,以前从来没有注意到,然后就查了一个它的帮助手册,其实以前也看过,只是大概浏览了一下,没有细细口味。
// gcc -o sscanTest sscanTest.c
#include
#include
int main(int argc, char **argv)
{
char sentence []="Rudolph is 12 years old";
char str [20];
char str2 [20];
char buf[128], buf2[128];
int i;
int a, b, c;
char sztime1[16] = "", sztime2[16] = "";
memset(buf, 0, 128);
sscanf (sentence,"%s %*s %d %s",str,&i, str2);
printf ("result100= %s -> %d -> %s\n",str, i, str2);
memset(buf, 0, 128);
sscanf("123456 ", "%3s", buf);
printf("result101= %s\n", buf);
memset(buf, 0, 128);
sscanf("123456 abcdedf", "%[^ ]", buf);
printf("result102= %s\n", buf);
memset(buf, 0, 128);
sscanf("123456abWWQcdedfBCDEF", "%*[1-9a-z]%s", buf);
printf("result103= %s\n", buf);
memset(buf, 0, 128);
sscanf("123456abWWQcdedfBCDEF", "%[1-9a-z]", buf);
printf("result1031= %s\n", buf);
memset(buf, 0, 128);
memset(buf2, 0, 128);
sscanf("bC123456abcdedfBCDEF", "%*[^A-Z]%c%*[0-9]%s", buf, buf2);
printf("result104= %s, %s\n", buf, buf2);
memset(buf, 0, 128);
memset(buf2, 0, 128);
//sscanf("bCDE123456abcdedfBCDEF", "%[a-z]%*[A-Z]%[^A-Z]", buf, buf2);
sscanf("bCDE123456abcdedfBCDEF", "%*[A-Za-z]%[^A-Z]", buf, buf2);
printf("result1041= %s , %s\n", buf, buf2);
memset(buf, 0, 128);
sscanf("", "%*[^/]/%[^@]", buf);
printf("result105= %s\n", buf);
memset(buf, 0, 128);
sscanf("hello,new world", "%*s%s", buf);
printf("result106= %s\n", buf);
// String of characters. This will read subsequent characters until a whitespace is found
// (whitespace characters are considered to be blank, newline and tab).
memset(buf, 0, 128);
sscanf("hello, new world", "%*s%s", buf);
printf("result1061= %s\n", buf);
sscanf("2006:03:18 - 2006:04:18", "%s - %s", sztime1, sztime2);
printf("result107= %s , %s\n", sztime1, sztime2);
memset(sztime1, 0, 16);
memset(sztime2, 0, 16);
sscanf("2006:03:18 - 2006:04:18", "%[0-9,:] - %[0-9,:]", sztime1, sztime2);
printf("result1071= %s , %s\n", sztime1, sztime2);
return 0;
}
以上测试结果显示为:
$ sscanTest.exe
result100= Rudolph -> 12 -> years
result101= 123
result102= 123456
result103= WWQcdedfBCDEF
result1031= 123456ab
result104= C, abcdedfBCDEF
result1041= 123456abcdedf ,
result105= 12DDabc/WDFF
result106= world
result1061= new
result107= 2006:03:18 , 2006:04:18
result1071= 2006:03:18 , 2006:04:18
参考网址对const char* s = ; sscanf( s, "%*[^/]/%[^@]", buf );
的匹配说明,个人感觉说明不太明确(也许是个人的理解不到位吧)
以至我写了上面的练习来体会sscanf表达式的用法
以下是个人理解,有不清楚或错误的地方可指正:
此表达式:"%*[^/]/%[^@]" 它分为两部分,1。需要过滤的部分(也就是去掉部分),2。需要保留给返回值部分
如何确定表达式拆分成几部分,则由%来确定
%*[^/]/为过滤部分, %*[^/]只是过滤了"iios",再加上/,就过滤了"iios/"(参考(*)说明)
%[^@]为返回值部分, 表示匹配到不是@字符为止的字符串,由于它是按char一个一个来匹配,一旦中止条件成立,就不再继续往下进行,也就是贪婪匹配结束
有关表达式可参考perl的,虽然sscanf的匹配模式没有正则表达式那么强大,但在一些场所还是很有效的
阅读(2855) | 评论(0) | 转发(0) |