2016-06-08 115 views
2

我在C++中有一個函數,它接收表示格式爲MM/DD/YYYY的日期的輸入字符串。由於我的環境的限制,該函數使用正則表達式的C實現。我試圖從字符串中提取年份,月份和日期。以C++語言在正則表達式中捕獲組

#include <stdarg.h> 
#include <string.h> 
#include <iostream> 
#include <regex.h> 
#include <sys/types.h> 

using namespace std; 


void convertDate(string input) 
{ 

    char pattern[100]; 
    regex_t preg[1]; 
    regmatch_t match[100]; 
    const char * reg_data = input.c_str(); 
    string year; 
    string month; 
    string day; 

    strcpy(pattern, "^([0-9]{1,2})/([0-9]{1,2})/([0-9]{4})$"); 
    int rc = regcomp(preg, pattern, REG_EXTENDED); 
    rc=regexec(preg, reg_data, 100, match, 0); 
    if(rc != REG_NOMATCH) 
    { 
     year = input.substr(match[3].rm_so, match[3].rm_eo); 
     month = input.substr(match[1].rm_so, match[1].rm_eo); 
     day = input.substr(match[2].rm_so, match[2].rm_eo); 
     cout << year << endl; 
     cout << month << endl; 
     cout << day << endl; 
    } 

} 

這裏是輸入/輸出的一些例子:

1) string input2 = "8/11/2014"; 
    convertDate(input2); 

    2014 
    8 
    11/2 

2) string input2 = "11/8/2014"; 
    convertDate(input2); 

    2014 
    11 
    8/20 

3) string input2 = "1/1/2014"; 
    convertDate(input2); 

    2014 
    1 
    1/2 

我不知道爲什麼一天拍攝長度爲4,當捕獲組指出它應該只被捕獲的正則表達式組1或2個字符是數字。另外,當這個月是正確的時候,爲什麼會有這個問題呢?他們使用相同的邏輯,看起來像。

我使用的文檔here

+0

你使用什麼編譯器和版本? – NathanOliver

+0

我正在使用使用C++ 11的在線編譯器。 [看這裏](http://www.tutorialspoint.com/compile_cpp11_online.php)@NathanOliver – Danzo

+0

行。那是gcc 5.3.1。我問是因爲[this](http://stackoverflow.com/questions/12530406/is-gcc-4-8-or-earlier-buggy-about-regular-expressions) – NathanOliver

回答

2

您正在使用.substr method錯誤。 substr的第二個參數應該是子字符串的長度,但是您要給它的結束索引。試試這個:

day = input.substr(match[2].rm_so, match[2].rm_eo - match[2].rm_so);