1.int regcomp(regex_t *compiled, const char *pattern, int cflags)
這個函數把指定的規則運算式pattern編譯成一種特定的資料格式compiled,這樣可以使匹配更有效。函數regexec會使用這個資料在目標文本串中進行模式比對。執行成功返回0。 regex_t:是一個結構體資料類型,用來存放編譯後的規則運算式,它的成員re_nsub用來儲存規則表達 式中的子規則運算式的個數,子規則運算式就是用圓括弧包起來的部分運算式。 pattern:是指向我們寫好的規則運算式的指標。 cflags:有如下4個值或者是它們或運算(|)後的值: REG_EXTENDED 以功能更加強大的擴充規則運算式的方式進行匹配。 REG_ICASE 匹配字母時忽略大小寫。 REG_NOSUB 不用儲存匹配後的結果。 REG_NEWLINE 識別分行符號,這樣'$'就可以從行尾開始匹配,'^'就可以從行的開頭開始匹配。
2. int regexec (regex_t *compiled, char *string, size_t nmatch, regmatch_t matchptr [], int eflags)
當我們編譯好規則運算式後,就可以用regexec 匹配我們的目標文本串了,如果在編譯規則運算式的時候沒有指定cflags的參數為REG_NEWLINE,則預設情況下是忽略分行符號的,也就是把整個文本串當作一個字串處理。執行成功返回0。 regmatch_t 是一個結構體資料類型,成員rm_so 存放匹配文本串在目標串中的開始位置,rm_eo 存放結束位置。通常我們以數組的形式定義一組這樣的結構。因為往往我們的規則運算式中還包含子規則運算式。數組0單元存放主規則運算式位置,後邊的單元依次存放子規則運算式位置。 compiled 是已經用regcomp函數編譯好的規則運算式。 string 是目標文本串。 nmatch 是regmatch_t結構體數組的長度。 matchptr regmatch_t類型的結構體數組,存放匹配文本串的位置資訊。 eflags 有兩個值 REG_NOTBOL 按我的理解是如果指定了這個值,那麼'^'就不會從我們的目標串開始匹配。總之我到現在還不是很明白這個參數的意義, 原文如下: If this bit is set, then the beginning-of-line operator doesn't match the beginning of the string (presumably because it's not the beginning of a line).If not set, then the beginning-of-line operator does match the beginning of the string. REG_NOTEOL 和上邊那個作用差不多,不過這個指定結束end of line。
3. void regfree (regex_t *compiled)
當我們使用完編譯好的規則運算式後,或者要重新編譯其他規則運算式的時候,我們可以用這個函數清空compiled指向的regex_t結構體的內容,請記住,如果是重新編譯的話,一定要先清空regex_t結構體。
4. size_t regerror (int errcode, regex_t *compiled, char *buffer, size_t length)
當執行regcomp 或者regexec 產生錯誤的時候,就可以調用這個函數而返回一個包含錯誤資訊的字串。 errcode 是由regcomp 和 regexec 函數返回的錯誤代號。 compiled 是已經用regcomp函數編譯好的規則運算式,這個值可以為NULL。 buffer 指向用來存放錯誤資訊的字串的記憶體空間。 length 指明buffer的長度,如果這個錯誤資訊的長度大於這個值,則regerror 函數會自動截斷超出的字串,但他仍然會返回完整的字串的長度。所以我們可以用如下的方法先得到錯誤字串的長度。 size_t length = regerror (errcode, compiled, NULL, 0);
EXAMPLES
#include <regex.h>
/* * Match string against the extended regular expression in * pattern, treating errors as no match. * * Return 1 for match, 0 for no match. */
intmatch(const char *string, char *pattern){ int status; regex_t re;
if (regcomp(&re, pattern, REG_EXTENDED|REG_NOSUB) != 0) { return(0); /* Report error. */ } status = regexec(&re, string, (size_t) 0, NULL, 0); regfree(&re); if (status != 0) { return(0); /* Report error. */ } return(1);}
The following demonstrates how the REG_NOTBOL flag could be used with regexec() to find all substrings in a line that match a pattern supplied by a user. (For simplicity of the example, very little error checking is done.)
(void) regcomp (&re, pattern, 0);/* This call to regexec() finds the first match on the line. */error = regexec (&re, &buffer[0], 1, &pm, 0);while (error == 0) { /* While matches found. */ /* Substring found between pm.rm_so and pm.rm_eo. */ /* This call to regexec() finds the next match. */ error = regexec (&re, buffer + pm.rm_eo, 1, &pm, REG_NOTBOL);}
===========================================================
參考拓展:
regcomp和regexec函數
The Open Group