Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

PCRE API 逐個拆解:核心函式的原型、參數與用法

PCRE 本質上是 NFA 引擎,否則無法提供與 Perl 完全一致的正則語法。但它同時也實作了 DFA,只是那屬於數學意義上的正則,語法能力較受限。

PCRE 共提供 19 個對外函式。以下依功能分組說明,範例取自其內附的測試程式 pcretest.c。

編譯類

pcre_compile

pcre *pcre_compile(const char *pattern, int options, const char **errptr,
                   int *erroffset, const unsigned char *tableptr);

把正則表達式編譯成內部表示,重複匹配多個字串時可大幅加速。參數中 pattern 是表達式本體,options 為 0 或選項組合,errptr 回傳錯誤訊息,erroffset 回傳錯誤位置,tableptr 指向字元對照表、可設為 NULL。

pcre_compile2

pcre *pcre_compile2(const char *pattern, int options, int *errorcodeptr,
                    const char **errptr, int *erroffset,
                    const unsigned char *tableptr);

與 compile 功能相同,多一個 errorcodeptr 參數用來回傳錯誤碼。需要程式化區分錯誤類型時用它。

查詢與解譯類

pcre_config

int pcre_config(int what, void *where);

查詢當前 PCRE 版本編譯時採用的各項設定,what 指定選項名稱,where 指向接收結果的空間。

pcre_fullinfo 系列則用來取得已編譯模式的詳細資訊,例如捕獲群組數量,通常作為配置 offset 陣列前的準備。

匹配類

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);

使用編譯好的模式進行匹配,採與 Perl 相似的演算法,回傳匹配結果。code 是編譯產物,extra 指向 pcre_extra 結構(可為 NULL),subject 與 length 描述待匹配字串及其位元組長度,startoffset 指定起始位置,ovector 是接收各子表達式偏移的整數陣列,ovecsize 為其容量。回傳值為捕獲組數加一,負值代表未匹配。

pcre_dfa_exec

int pcre_dfa_exec(const pcre *code, const pcre_extra *extra, const char *subject,
                  int length, int startoffset, int options,
                  int *ovector, int ovecsize,
                  int *workspace, int wscount);

同樣是匹配,但走 DFA 路徑,只對目標串掃描一次,因此與 Perl 行為不完全相容(例如不支援回溯相關語法)。額外需要 workspace 工作區陣列。優勢在於效能穩定、不會因回溯而爆掉。

取用捕獲結果類

pcre_copy_substring:依編號取出捕獲字串,拷貝到呼叫端提供的緩衝區。

int pcre_copy_substring(const char *subject, int *ovector, int stringcount,
                        int stringnumber, char *buffer, int buffersize);

pcre_copy_named_substring:依名稱取出捕獲字串,適合有命名群組((?<name>...))的表達式。

int pcre_copy_named_substring(const pcre *code, const char *subject, int *ovector,
                              int stringcount, const char *stringname,
                              char *buffer, int buffersize);

pcre_get_substring 與 pcre_get_named_substring:與上述 copy 版本功能相同,但由 PCRE 自行配置記憶體,用完必須以 pcre_free_substring 釋放。

void pcre_free_substring(const char *stringptr);

copy 與 get 兩組的取捨很清楚:copy 由你管理緩衝區,不會洩漏但得自己估算大小;get 免去容量煩惱,代價是配對的釋放責任。搭配 malloc 自訂管理器的專案,通常傾向用 copy。

其他

剩下的函式多為記憶體管理與輔助用途:pcre_free 釋放編譯產物、pcre_maketables 依地區設定產生字元對照表、pcre_study 對常用模式做預先分析以加速後續匹配、pcre_version 回報版本字串等。

實務上的典型調用順序是:pcre_compile(或 study)→ pcre_exec 迴圈匹配 → 以 copy/get 系列取出需要的片段 → pcre_free 收尾。把這條主線記住,其餘函式都是按需查閱即可。

Copyright © Linux教程網 All Rights Reserved