2011-04-18 127 views
1

我使用Boost.Regex來實現這樣的目標:搜索「|」然後拿走「|」的左邊部分並把它放在一個字符串中,與右邊相同:使用正則表達式搜索C++

string s1; 
string s2; 
who | sort 

此後s1應該是「誰」,s2應該是「排序」。
如果我記得好,它在Python中是可行的,我如何在Boost中使用正則表達式來做到這一點?

謝謝。

回答

2
#include <boost/algorithm/string.hpp> 
std::vector<std::string> strs; 
boost::split(strs, "string to split", boost::is_any_of("|")); 

Split a string in C++?

2

這裏的簡短的樣本:

#include <iostream> 
#include <boost/regex.hpp> 

int main() 
{ 
    // expression 
    boost::regex exrp("(.*)\\|(.*)"); 
    boost::match_results<std::string::const_iterator> what; 
    // input 
    std::wstring input = "who | sort"; 
    // search 
    if(regex_search(input, what, exrp)) { 
    // found 
    std::string s1(what[1].first, what[1].second); 
    std::string s2(what[2].first, what[2].second); 
    } 

    return 0; 
} 

另外,你也許想看看在Boost.Tokenizer