2015-04-17 139 views
1

我是新來的正則表達式和C + + 11。爲了配合這樣的表達式:正則表達式在C++ 11 vs PHP

TYPE SIZE NUMBER ("regina s x99");

我建了一個正則表達式看起來像這樣的:

\b(regina|margarita|americaine|fantasia)\b \b(s|l|m|xl|xxl)\b x([1-9])([0-9])

在我的代碼我這樣做是爲了嘗試正則表達式:

std::string s("regina s x99"); 
std::regex rgx($RGX); //$RGX corresponds to the regex above 
if (std::regex_match(s, rgx)) 
std::cout << "It works !" << std::endl; 

這段代碼扔了std::regex_error,但我不知道它來自哪裏..

感謝,

+1

使用GCC 4.9.0:http://stackoverflow.com/questions/15671536/why-does-this-c11-stdregex-example-throw-a-regex-error-exception –

+2

@Nicolas爲什麼在主題行中有PHP引用? – Steephen

+0

@stribizhev我正在編譯與g ++ - 4.9和仍然是相同的錯誤。 –

回答

1

該作品在C++ 11模式下使用g ++(4.9.2):

std::regex rgx("\\b(regina|margarita|americaine|fantasia)\\b\\s*(s|l|m|xl|xxl)\\b\\s*x([1-9]*[0-9])"); 

這將捕獲thre e組:regina s 99它與TYPE SIZE NUMBER模式匹配,而您的原始捕獲的四組regina s 9 9並且具有NUMBER兩個值(可能這是您想要的)。

Demo on IdeOne

+0

謝謝!這工作:) –

+0

最後一個組可以(也可能應該)被調整一點取決於你想匹配的數字的範圍(如果它有一個前導0或不是。也許它應該是'x([1-9 ] + [0-9] *)'爲'1到N' – jpw

0

有在這一行一個錯字在問題:

if (std::reegex_match(s, rgx)) 

更多了,我不知道你有什麼與此變量傳遞:$RGX

更正程序如下:

#include<regex> 
#include<iostream> 
int main() 
{ 
    std::string s("regina s x99"); 
std::regex rgx("\\b(regina|margarita|americaine|fantasia)\\b \\s*(s|l|m|xl|xxl)\\b \\s*x([1-9])([0-9])"); //$RGX corresponds to the regex above 
if (std::regex_match(s, rgx)) 
std::cout << "It works !" << std::endl; 
else 
    std::cout<<"No Match"<<std::endl; 
} 
+0

是的,複製/粘貼在VMWare和MAC Os X之間不起作用,在我的代碼中沒有輸入錯誤,變量$ RGX的確不存在於我的代碼中,我不想再次重寫正則表達式。我認爲這樣更清楚。 –

+0

@NicolasCharvozKurzawa感謝知道我的答案可以幫助你! – Steephen

+0

@Steephen你需要逃避你的斜槓或這永遠不會匹配。 –

1

在C++字符串中,\字符非常特殊,需要進行轉義才能將其傳遞到正則表達式引擎,而不是由編譯器解釋。

所以,你要麼需要使用\\b

std::regex rgx("\\b(regina|margarita|americaine|fantasia)\\b \\b(s|l|m|xl|xxl)\\b x([1-9])([0-9])"); 

或使用原始的字符串,這意味着\不是特殊的,並不需要進行轉義:

std::regex rgx(R"(\b(regina|margarita|americaine|fantasia)\b \b(s|l|m|xl|xxl)\b x([1-9])([0-9]))");