[英]C++ regex string capture
Tring讓C ++正則表達式字符串捕獲工作。 我已經嘗試了Windows與Linux的所有四種組合,Boost與本機C ++ 0x11。 示例代碼是:
#include <string>
#include <iostream>
#include <boost/regex.hpp>
//#include <regex>
using namespace std;
using namespace boost;
int main(int argc, char** argv)
{
smatch sm1;
regex_search(string("abhelloworld.jpg"), sm1, regex("(.*)jpg"));
cout << sm1[1] << endl;
smatch sm2;
regex_search(string("hell.g"), sm2, regex("(.*)g"));
cout << sm2[1] << endl;
}
最接近的是帶有Boost(1.51.0)的g ++(4.7)。 在那里,第一個cout輸出預期的abhelloworld.
但第二個cout沒什么。
g ++ 4.7 with -std = gnu ++ 11 and <regex>
而不是<boost/regex.hpp>
產生輸出。
使用本機<regex>
Visual Studio 2012會產生關於不兼容的字符串迭代器的異常。
帶有Boost 1.51.0和<boost/regex.hpp>
Visual Studio 2008會產生關於“標准C ++庫無效參數”的異常。
這些錯誤是在C ++正則表達式中,還是我做錯了什么?
這些錯誤是在C ++正則表達式中,還是我做錯了什么?
如其他答案所述,gcc不支持<regex>
。 至於其他問題,你的問題是你傳遞的是臨時字符串對象 。 將您的代碼更改為以下內容:
smatch sm1;
string s1("abhelloworld.jpg");
regex_search(s1, sm1, regex("(.*)jpg"));
cout << sm1[1] << endl;
smatch sm2;
string s2("hell.g");
regex_search(s2, sm2, regex("(.*)g"));
cout << sm2[1] << endl;
您的原始示例進行編譯,因為regex_search
采用臨時對象可以綁定的const引用,但是, smatch
僅將迭代器存儲到不再存在的臨時對象中。 解決方案是不通過臨時工。
如果你在[§28.11.3/ 5]中查看C ++標准,你會發現以下內容:
返回:regex_search的結果(s.begin(),s.end(),m,e,flags)。
這意味着在內部,只使用傳入的字符串的迭代器 ,因此如果傳入臨時對象,將使用無效的迭代器,並且不存儲實際的臨時對象。
GCC還不支持<regex>
。 請參閱手冊
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.