2016-10-22 21 views
0

With std::regex_replace
我可以使用「$」匹配單詞的末尾,然後附加其他字符。

std::cout << std::regex_replace("word",std::regex("$"),"s") << '\n'; 
//prints: words 

由於結果與原始輸入不同,我假定正則表達式已匹配。

然而,

std::cout << std::boolalpha; 
std::cout << std::regex_match("word",std::regex("$")) << '\n'; 
//prints: false 

怎麼會是正則表達式不匹配,但regex_replace能夠進行替換?


我也嘗試添加一個*爲0個或多個字符,而是拋出異常:

std::cout << std::regex_match("word",std::regex("*$")) << '\n'; 
    std::cout << std::regex_replace("word",std::regex("*$"),"s") << '\n'; 

回答

1

注意regex_match只正則表達式匹配成功到整個字符序列,而std :: regex_search將成功匹配子序列。

你想要regex_search匹配子序列。 $與全部非空字符串不匹配,但匹配非空字符串的(零長度)子字符串。

相關問題