2012-04-23 87 views
4

對於正則表達式,我正在使用regex.hPOSIX)。 C中有正則表達式匹配的選擇方法嗎?如何在C中輕鬆獲取正則表達式選擇?

我可以很容易地檢查正則表達式,但如果我需要檢索匹配的值,我必須手動查找並存儲它。

{{()*(([[:alnum:]]+\\.)*)?[[:alnum:]]+()*}} 

這個正則表達式尋找雙花括號中的任何變量匹配。但我只需要字符串中最中心的項目。 如何用C中的正則表達式檢索值?

回答

4

您需要傳入一組regmatch_t s表示正則表達式可以填充匹配的索引。用一個命令行參數(要測試的字符串)嘗試下面的程序。

一旦你有了匹配的指數,它應該是相當容易的拉出你的東西。 (注:matches[0]將是整個表達式的匹配,所以子表達式開始於matches[1]。)

#include <stdlib.h> 
#include <stdio.h> 
#include <regex.h> 

int main(int argc, char* argv[]) 
{ 
    const char* pattern = "{{()*(([[:alnum:]]+\\.)*)?[[:alnum:]]+()*}}"; 
    regex_t rex; 
    int rc; 

    if ((rc = regcomp(&rex, pattern, REG_EXTENDED))) { 
     fprintf(stderr, "error %d compiling regex\n", rc); 
     /* retrieve error here with regerror */ 
     return -1; 
    } 

    regmatch_t* matches = malloc(sizeof(regex_t) * (rex.re_nsub + 1)); 

    if ((rc = regexec(&rex, argv[1], rex.re_nsub + 1, matches, 0))){ 
     printf("no match\n"); 
     /* error or no match */ 
    } else { 
     for(int i = 0; i < rex.re_nsub; ++i) { 
      printf("match %d from index %d to %d: ", i, matches[i].rm_so, 
        matches[i].rm_eo); 
      for(int j = matches[i].rm_so; j < matches[i].rm_eo; ++j) { 
       printf("%c", argv[1][j]); 
      } 
      printf("\n"); 
     } 
    } 

    free(matches); 
    regfree(&rex); 

    return 0; 
}