【第三方库】c++ 使用正则表达式库 pcre

1、为什么使用pcre而不是用自身的标准库regex?

引用:

PCRE benefits from some optimizations known as start-up optimizations which are configured to be enabled by default. These optimizations include:

  1. A subject pre-scan for unanchored patterns (if a starting point is not found engine doesn't even bother to go through matching process.)
  2. Studying pattern to ensure that minimum length of subject is not shorter than pattern itself
  3. Auto-possessification
  4. Fast failure (if a specific point is not found engine doesn't even bother to go through matching process.)

2、使用步骤

  1. 下载pcre,可以是源码,也可以是编译好的文件
  2. 添加头文件引用 ,注意要加宏
    #define PCRE_STATIC
    #include "pcre/pcre.h"

     

  3. 添加库引用,注意库路径,或者在工程里加
    #pragma comment(lib, "pcre.lib")

     

  4. 示例程序
    int main()
    {
    	int erroroffset;
    	int offsetcount;
    	int offset[(10)*3];
    	const char * error;
    	char *cm_pattern = "^1(39|38|37|36|35|34|59|50|51|58|57|88|87|52|82|47)[0-9]{8}";
    	char *un_pattern = "^1(30|31|32|55|56|85|86|45)[0-9]{8}";
    	char *cdma_pattern = "^1(33|53|80|81|89|77)[0-9]{8}";
    	char *isnum_pattern = "^1[0-9]{10}$";
    	char str[15] = {0};
    	pcre *cmPN, *unPN, *cdmaPN, *isnumPN;
    	int cm, un, cdma, isnum;
    
    	printf("\n手机号码运营商检测,请输入您的手机号码:\n>");
    	scanf("%s", str);
    
    	cmPN = pcre_compile(cm_pattern, 0, &error, &erroroffset, NULL);
    	unPN = pcre_compile(un_pattern, 0, &error, &erroroffset, NULL);
    	cdmaPN = pcre_compile(cdma_pattern, 0, &error, &erroroffset, NULL);
    	isnumPN = pcre_compile(isnum_pattern, 0, &error, &erroroffset, NULL);   
    	if (cmPN == NULL
    		&&unPN == NULL
    		&&cdmaPN == NULL
    		&&isnumPN == NULL){
    			printf("正则表达式错误!\n");
    	}
    
    	isnum = pcre_exec(isnumPN, NULL, str, strlen(str), 0, 0, offset, (10)*3);
    	if (isnum < 0){
    		if (isnum == PCRE_ERROR_NOMATCH){
    			printf("手机号码长度不是11位数!\n");
    		}else{
    			printf("正则表达式匹配错误!\n");
    		}
    		system("pause");
    		return 1;
    	}
    
    	cm = pcre_exec(cmPN, NULL, str, strlen(str), 0, 0, offset, (10)*3);
    	if (cm > 0){
    		printf("您输入的是:中国移动号码。\n");
    		system("pause");
    		return 0;
    	}
    	un = pcre_exec(unPN, NULL, str, strlen(str), 0, 0, offset, (10)*3);
    	if (un > 0){
    		printf("您输入的是:中国联通号码。\n");
    		system("pause");
    		return 0;
    	}
    	cdma = pcre_exec(cdmaPN, NULL, str, strlen(str), 0, 0, offset, (10)*3);
    	if (cdma > 0){
    		printf("您输入的是:中国电信号码。\n");
    		system("pause");
    		return 0;
    	}
    
    	pcre_free(cmPN);
    	pcre_free(cmPN);
    	pcre_free(cdmaPN);
    
    	system("pause");
    	return 0;
    }

     

 

你可能感兴趣的:(第三方库)