Pravin Holkar Pravin Holkar - 2 months ago 12
C++ Question

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

I want to split the string

"Input\temp.csv:1:14"
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

Input\temp.csv
1
14

Answer

This should work:

[live]

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;
Comments