【第三方庫】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;
    }

     

 

發佈了367 篇原創文章 · 獲贊 183 · 訪問量 34萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章