nginx模块正则表达式无法匹配

时间:2014-07-04 13:39:55

标签: regex nginx

嗨,大家好我试图为nginx构建一个模块,需要匹配一个子串这里是我用来尝试匹配

int match_chan(ngx_http_request_t *r, ngx_pool_t *temp_pool, ngx_str_t *body, ngx_str_t *channel) {
    u_char errstr[NGX_MAX_CONF_ERRSTR];
    ngx_regex_compile_t *rc;
    int captures[2];
    if ((rc = ngx_pcalloc(temp_pool, sizeof(ngx_regex_compile_t))) == NULL) {
        ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "unable to allocate memory to compile agent patterns");
        return 0;
    }
    //ngx_memzero(rc, sizeof(ngx_regex_compile_t));
    ngx_str_t pat = ngx_string("test(:|%3[Aa])([a-zA-Z0-9]+)");
    rc->pattern = pat;
    rc->pool = temp_pool;
    rc->err.len = NGX_MAX_CONF_ERRSTR;
    rc->err.data = errstr;
    if (ngx_regex_compile(rc) != NGX_OK) {
        ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "unable to compile regex pattern %V", rc->pattern);
        return 0;
    }
    ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "%V, %V", &pat, body);
    if (ngx_regex_exec(rc->regex, body, captures, 2) >= 0) {
        ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "It Matched");
        //ngx_memcpy(channel->data, body->data + captures[0], body->len);
        return 1;
    }
    ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "It did not match");
    return 0;
}

ngx_str_t *channel = NULL;
if(match_chan(r, temp_pool, aux, channel)) {
  //ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, " match: %c", match);
}

并且传递的消息看起来像这样

2014/07/04 13:28:49 [error] 10695#0: *38 test:([a-z0-9]+), MSG%0Atest%3Ahello%0A%0A%0Awins%00
2014/07/04 13:28:49 [error] 10695#0: *38 It did not match

取自nginx日志

我在一个纯C应用程序中测试了正则表达式并且运行良好我认为nginx类似但我猜它有它的差异

我看了遍布谷歌和香港专业教育学院试过看nginx模块仍然没有运气请帮助我:))

由于 戴夫

1 个答案:

答案 0 :(得分:1)

问题是您尝试匹配的字符串是URL编码的,因此它与提供的模式不匹配。有两种选择:

  • 构造一个正则表达式,以便它也匹配编码的字符串("test(:|%3[Aa])([a-zA-Z0-9]+)"将匹配未转义和转义的表格);

  • Unescape您匹配的字符串。在nginx中,这是通过ngx_unescape_uri()函数完成的。