2013-01-07 39 views
0

我最近寫的正則表達式解析我的文件提取含量研究的內容,但一個是在.NET和我剛纔使用Boost我的C++項目開工。使用boost從字符串

我有類似如下行,這是一個的std :: string
123 12 E

,我要解析,並得到以下。

浮=第一位
浮=第二位
串=第三個字母

因爲我一直在使用正則表達式的經驗,我知道正則表達式是什麼

const char* Regex = "^[[:space:]]*(\\d{1,3})[[:space:]]*(\\d{1,2})[[:space:]]*([NSEW])[[:space:]]*"

但我我不知道如何使用這個提升來從我的行中提取三件事情。我試着在Boost網站上閱讀例子,似乎沒有回答我的問題,因爲我不得不停下來找到這個小細節。我如何使用上面的正則表達式來使用Boost Regex在三個變量中獲得我的結果?

+2

'的sscanf( 「%F%F%C」)'不能滿足您的需求? – nothrow

+1

'float a,b; std :: string s; std :: cin >> a >> b >> s;'? –

+0

使用'std :: istringstream'會更容易,就像這樣:'std :: istringstream s(「123 12 E」); S >> float1 >> FLOAT2 >>字符串1;' – Angew

回答

1

http://www.boost.org/doc/libs/1_52_0/libs/regex/doc/html/boost_regex/introduction_and_overview.html給出示例匹配的。你最終會得到一個match_results結構,你可以從中獲得匹配結果。

未經測試的代碼

const char *str = "123 12 E"; 
boost::regex re ("^(\\d{1,3}) (\\d{1,2}) ([NSEW])$"); 
boost::cmatch mr; 
if (boost::regex_match (str, mr, re)) { 
    std::cout << "There were: " << mr.size() - 1 << " fields matched" << std::endl; 
    std::cout << "First part: " << mr[1] << std::endl; 
    } 
相關問題