sscanf通过正则表达式从字符串获取参数

一行代码抵千言。字符串里面有登录名和密码,用特殊字符分隔。现在需要从这个字符串里面读取数据。

需要用到sscanf函数,以及正则表达式。

当然,这里的正则表达式并非完美(没有过滤非法字符、没有限制字符个数,等等)

但是,这个Demo只是是满足我们目前的需求的。当前使用,足以。

#include <stdio.h>
int main(void)
{

/* 
char buffer[] = "2423&dfgdfg&329234";
char str1[20], str2[20], str3[20];
sscanf(buffer, "%[^&]&%[^&]&%s", str1, str2, str3);
printf("str1:%s \r\n", str1);
printf("str2:%s \r\n", str2);
printf("str3:%s \r\n", str3);
*/

 

char strKey1[32]={};
char strValue1[32]={};
char strKey2[32]={};
char strValue2[32]={};
char strKey3[32]={};
char strValue3[32]={};
int iValue3=0;

printf("hello world----111----->>>\r\n");
sscanf(
"username=henry1&password=123456&act=1", "%[^=]=%[^&]&%[^=]=%[^&]&%[^=]=%d", strKey1,strValue1, strKey2, strValue2, strKey3, &iValue3);
printf(
"strKey1:%s, strValue1:%s \r\n", strKey1, strValue1); printf("strKey2:%s, strValue2:%s \r\n", strKey2, strValue2); printf("strKey3:%s, strValue3:%d \r\n", strKey3, iValue3); printf("hello world----222----->>>\r\n"); return 0; }

猜你喜欢

转载自www.cnblogs.com/music-liang/p/12927252.html