I'm trying to split a string based on space except when inside quotes. This is the regex I found online (\\w |\".*?\")
. However, when I try to use std::regex
to split a string, I get only empty strings.
This is the code I have to split:
std::regex exp("[^\\s\"'] |\"([^\"]*)\"|'([^']*)'");
std::sregex_token_iterator itr(s.begin(), s.end(), exp, -1);
std::sregex_token_iterator end;
for (; itr != end; itr )
std::cout << *itr << std::endl;
This prints out only " "
when I pass a string like "A "B C" 123"
. What could I be doing wrong?
CodePudding user response:
From documentation for std::sregex_token_iterator
:
submatch - the index of the submatch that should be returned. "0" represents the entire match, and "-1" represents the parts that are not matched (e.g, the stuff between matches).
Since you're passing -1, it means you're printing the parts that didn't match, not the parts that matched.