Search code examples
c++stringsplitquotes

Split a string a string using special formatting in c++


I'm trying to split a string like this :

"aaaaaaaa"\1\"bbbbbbbbb"

with the quotes included, in order to obtain aaaaaaaa bbbbbbbbb.

I found different methods to get the split of the string but the presence of quotes and slash causes many problems.

For example if i use string.find i can't use string.find("\1\");

does anyone know how to help me ? thank you


Solution

  • #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;
        }
    }
    

    expected results:

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