龙空技术网

该怎么使用C语言中的sscanf()函数正则表达式?

职业小宝引导师 185

前言:

而今朋友们对“c语言编写s函数”大约比较重视,朋友们都想要知道一些“c语言编写s函数”的相关内容。那么小编在网络上搜集了一些关于“c语言编写s函数””的相关内容,希望大家能喜欢,大家一起来了解一下吧!

sscanf()函数实现:

不管接触过任何编程语言也好,学过正则表达式的都对sscanf()的使用并不陌生了。如何通过sscanf将已知的字符串通过格式化匹配出有效的信息?下面我把要实现对象的方法和作用意义给列出来,如下所示:

格式

作用

%*s或%*d

跳过数据

%[width]s

读指定宽度的数据

%[a-z]

匹配a到z中任意字符(尽可能多的匹配)

%[aBc]

匹配a、B、c中一员,贪婪性

%[^a]

匹配非a的任意字符,贪婪性

%[^a-z]

表示读取除a-z以外的所有字符

以上有六种方法,每种方法都来实现以下:

函数原型为:int sscanf(const char *const_Buffer, const char*const _Format, ...)

作用:从一个字符串中读进与指定格式相符的数据的函数

第1种方法:

利用%*s或%*d的格式实现跳过数据:

代码如下所示:

#define _CRT_SECURE_NO_WARNINGS#include <stdio.h>#include <string.h>#include <stdlib.h>void test(){	char * str1 = "666helloworld";	char temp1[128] = { 0 };	sscanf(str1, "%*d%s", temp1);	printf("%s\n", temp1); // 得到的是helloworld	printf("---------------\n");	char * str2 = "helloworld666";	char temp2[128] = { 0 };	sscanf(str2, "%*[a-z]%s", temp2);	printf("%s\n", temp2); // 得到的是666}int main(){	test();	system("pause");	return 0;}
结果图为:第2种方法:

通过%[width]s格式进行读指定宽度的数据:

代码如下所示:

#define _CRT_SECURE_NO_WARNINGS#include <stdio.h>#include <string.h>#include <stdlib.h>void test(){	char * str1 = "666helloworld";	char temp1[128] = { 0 };	sscanf(str1, "%8s", temp1);	printf("%s\n", temp1); // 得到的是666hello}int main(){	test();	system("pause");	return 0;}
第3种方法:

通过%[a-z]格式进行匹配a到z中任意字符(尽可能多的匹配):

代码如下所示:

#define _CRT_SECURE_NO_WARNINGS#include <stdio.h>#include <string.h>#include <stdlib.h>void test(){	char * str1 = "666helloworld";	char temp1[128] = { 0 };	sscanf(str1, "%*d%[a-z]", temp1);	printf("%s\n", temp1); // 得到的是helloworld}int main(){	test();	system("pause");	return 0;}
第4种方法:

通过%[aBc]格式进行匹配a、B、c中的一员,贪婪性正则表达式

代码如下所示:

#define _CRT_SECURE_NO_WARNINGS#include <stdio.h>#include <string.h>#include <stdlib.h>void test(){	char * str1 = "abccabchelloworld"; 	char temp1[128] = { 0 };	sscanf(str1, "%[abc]", temp1); //  如果刚开始就遇到匹配失败,后续则不再匹配	printf("%s\n", temp1); // 得到的是abccabc}int main(){	test();	system("pause");	return 0;}
第5种方法:

通过方法: %[^a]格式进行匹配非a的任意字符,也属于贪婪性正则表达式

代码如下所示:

#define _CRT_SECURE_NO_WARNINGS#include <stdio.h>#include <string.h>#include <stdlib.h>void test(){	char * str1 = "abccabchelloworld"; 	char temp1[128] = { 0 };	sscanf(str1, "%[^c]", temp1); //  如果匹配到字符,则字符后面的不在进行匹配	printf("%s\n", temp1); // 得到的是ab}int main(){	test();	system("pause");	return 0;}
第6种方法:

通过%[^a-z]格式,进行匹配读取除a-z以外的所有字符

代码如下所示:

#define _CRT_SECURE_NO_WARNINGS#include <stdio.h>#include <string.h>#include <stdlib.h>void test(){	char * str1 = "hello52wo3rld"; 	char temp1[128] = { 0 };	sscanf(str1, "%[^0-9]", temp1); //  如果匹配到字符,则字符后面的不在进行匹配	printf("%s\n", temp1); // 得到的是hello}int main(){	test();	system("pause");	return 0;}

通过以上6种常见的正则表达式方法,尤其在编写代码的时候,要完成某个字符串的拼接,提取等要求,这就可以利用这些表达式来解决字符串的一些问题了。

标签: #c语言编写s函数