2016-06-19 51 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

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