Pravin Holkar Pravin Holkar - 1 year ago 89
C++ Question

Split a string having colon and store in vector using regex pattern in C++

I want to split the string

separated by colon and store the results in a vector. What should the regex look like? Or do I need an entirely different approach?

sInpFileName = "Input\temp.csv:1:14";

regex colon(?);
vector<string> MyVector(sregex_token_iterator(sInpFileName.begin(), sInpFileName.end(), colon, 1), sregex_token_iterator());

MyVector should have three element as


Answer Source

This should work:


std::string sInpFileName = "Input\\temp.csv:1:14";

std::regex re{"([^:]+)"};
std::regex_token_iterator<std::string::iterator> it{sInpFileName.begin(), sInpFileName.end(), re, 1};
decltype(it) end{};
while (it != end) std::cout << *it++ << std::endl;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download