0
点赞
收藏
分享

微信扫一扫

C语言 正则表达式邮箱验证(pcre库)


本程序与2020.3.12在DEV-C++编译器运行成功,邮箱验证用下面两个函数即可。

PCRE接口介绍

(1). pcre_compile

pcre *pcre_compile(const char *pattern, int options,
const char **errptr, int *erroffset,
const unsigned char *tableptr);
功能:编译指定的正则表达式
参数:pattern, 输入参数,将要被编译的字符串形式的正则表达式
options, 输入参数,用来指定编译时的一些选项
errptr, 输出参数,用来输出错误信息
erroffset, 输出参数,pattern中出错位置的偏移量
tableptr, 输入参数,用来指定字符表,一般情况用NULL, 使用缺省的字符表
返回值:被编译好的正则表达式的pcre内部表示结构

(2). pcre_exec

int pcre_exec(const pcre *code, const pcre_extra *extra,
const char *subject, int length, int startoffset,
int options, int *ovector, int ovecsize);
功能:用来检查某个字符串是否与指定的正则表达式匹配
参数: code, 输入参数,用pcre_compile编译好的正则表达结构的指针
extra, 输入参数,用来向pcre_exec传一些额外的数据信息的结构的指针
subject, 输入参数,要被用来匹配的字符串
length, 输入参数, 要被用来匹配的字符串的指针
startoffset, 输入参数,用来指定subject从什么位置开始被匹配的偏移量
options, 输入参数, 用来指定匹配过程中的一些选项
ovector, 输出参数,用来返回匹配位置偏移量的数组
ovecsize, 输入参数, 用来返回匹配位置偏移量的数组的最大大小
返回值:匹配成功返回非负数,匹配错误返回负数

编译之前的准备:

C语言正则库使用方法
这里使用的是GnuWin32编译的版本,我把需要的文件放到压缩包里了。
1、libpcre.dll.a复制到Dev-Cpp\MinGW64\lib
2、pcre.h 复制到Dev-Cpp\MinGW64\include
3、编译后运行需要pcre3.dll,复制到编译后目标代码目录下
4、编译选项添加 -lpcre

文件的

代码如下:

#include<stdio.h>
#include<pcre.h>
#include<string.h>
int main()
{
const char* errptr=NULL;
int erroffset;
pcre *pPcre=pcre_compile("^([a-z0-9A-Z]+[-|_|\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\.)+[a-zA-Z]{2,}$",
0,&errptr,&erroffset,NULL);
char email_address[50];
while(scanf("%s",email_address))
{
if(pcre_exec(pPcre,NULL,email_address,strlen(email_address),0,0,NULL,0)<0)
printf("邮箱格式错误\n");
else
printf("邮箱格式正确\n");
}
free(pPcre);
return 0;
}

 

举报

相关推荐

0 条评论