2016-06-19 65 views
0

我試圖分裂像這樣的字符串中使用特殊格式的字符串:分割字符串在C++中

「AAAAAAAA」 \ 1 \「bbbbbbbbb」

用引號包含,以獲得aaaaaaaa bbbbbbbbb。

我發現不同的方法來獲取字符串的分割,但引號和斜槓的存在會導致很多問題。例如,如果我使用string.find我不能使用string.find(「\ 1 \」);如果我使用string.find我不能使用string.find(「\ 1 \」);我不能使用string.find。

沒有人知道如何幫助我嗎?謝謝

+0

你需要逃避'\\''在你的代碼:' '\\''。 –

+0

只需使用string.find(「1」);因爲\「用於在字符串內標記qoutes,所以它被稱爲轉義序列字符串。只要把\」當成「在一個字符串內即可! – meJustAndrew

回答

1
#include <iostream> 
#include <string> 
#include <regex> 

int main() 
{ 
    // build a test string and display it 
    auto str = std::string(R"text("aaaaaaaa"\1\"bbbbbbbbb")text"); 
    std::cout << "input : " << str << std::endl; 

    // build the regex to extract two quoted strings separated by "\1\" 

    std::regex re(R"regex("(.*?)"\\1\\"(.*?)")regex"); 
    std::smatch match; 

    // perform the match 
    if (std::regex_match(str, match, re)) 
    { 
     // print captured groups on success 
     std::cout << "matched : " << match[1] << " and " << match[2] << std::endl; 
    } 
} 

預計業績:

input : "aaaaaaaa"\1\"bbbbbbbbb" 
matched : aaaaaaaa and bbbbbbbbb 
+0

非常感謝,它效果很好。 –