1. 程式人生 > >Nginx模組開發中使用PCRE正則表示式匹配

Nginx模組開發中使用PCRE正則表示式匹配

Nginx內部對pcre庫的常用操作進行了封裝. 封裝的原始碼位於nginx/src/core/ngx_regex.c, 同時將pcre內使用的記憶體池更變為了Nginx的記憶體池.

  • pcre_compile:

    Nginx封裝了pcre_compile方法. 方法名為ngx_regex_compile.

    ngx_regex_compile方法的引數需要傳入一個ngx_regex_compile_t來進行編譯正則等操作.

    ngx_regex_compile_t結構如下:

    typedef struct {
        ngx_str_t     pattern; // 正則
        ngx_pool_t    *pool;   // 每個request分配的記憶體池
        ngx_int_t     options; // pcre options
    
        ngx_regex_t   *regex;  // 編譯完畢後的pcre例項
        int           captures;
        int           named_captures;
        int           name_size;
        u_char       *names;
        ngx_str_t     err;     // 錯誤資訊
    } ngx_regex_compile_t;`
    

    當編譯正則成功時會返回NGX_OK並且會在內部呼叫pcre_study來進一步提高正則匹配效能. 失敗時會返回NGX_ERROR. 同時失敗的錯誤資訊會儲存在err成員變數中.

  • pcre_exec

    Nginx同樣封裝了pcre_exec封裝後的方法名為:ngx_regex_exec 原始碼位於nginx/src/core/ngx_regex.h檔案中:

    #define ngx_regex_exec(re, s, captures, size)                                \
        pcre_exec(re->code, re->extra, (const char *) (s)->data, (s)->len, 0, 0, \
                  captures, size)
    

    可以看到引數re要求的是ngx_regex_compile_t中的regex成員變數. 而被搜尋的字串被替換成了Nginx內部的字串型別ngx_str_t. 同時也將Nginx內部不常用的搜尋偏移以及選項設定為成0. 如果仍需要使用偏移以及選項的話可以直接使用pcre_exec來跳過Nginx的封裝.

Refs: