2013-03-03 46 views
1
#include <iostream> 
#include <string> 
#include <regex> 

using namespace std; 

void Test(const char* str, const char* regExpression) 
{ 
    regex rx(regExpression); 
    bool match = regex_match(str, rx); 
    bool search = regex_search(str, rx); 

    cout << "String: " << str << " expression: " << regExpression << 
     " match: " << (match ? "yes" : "no ") << 
     " search: " << (search ? "yes" : "no ") << endl; 
} 


int main() 
{ 
    Test("a", "a"); 
    Test("a", "abc"); 
    return 0; 
} 

結果克++:正則表達式以g ++和VS2012

String: a expression: a match: yes search: no 
String: a expression: abc match: no search: no 

結果VS2012:

String: a expression: a match: yes search: yes 
String: a expression: abc match: no search: no 

這是正確的結果?另外,regex_match和regex_search有什麼區別?

回答

2

VS2012的結果是正確的。 _match檢查您的字符串是否與表達式匹配,_search檢查字符串的某個子字符串是否與表達式匹配。

"a""a"的任何子串都不匹配表達式​​。

(我無法找到相關的SO問題,但gcc的(更確切地說,的libstdC++的)正則表達式的實現被稱爲是越野車和不完整的。)

+0

可恥的是我,我只是用不正確的順序測試參數:( – 2013-03-03 12:15:11

+1

不需要SO問題;它在[GCC的標準庫支持表](http://gcc.gnu.org/onlinedocs/libstdc++/manual/status.html#status.iso.200x)中有描述(參見' 28,正則表達式') – jogojapan 2013-03-03 12:15:16

+0

請參閱http://stackoverflow.com/questions/12530406/is-gcc4-7-buggy-about-regular-expressions/12665408#12665408和http://stackoverflow.com/a/4716974/ 981959並加載更多問題 – 2013-03-03 16:45:39