I want to do 2 things at the same time: Match a string against a pattern and extract groups.
The string consists of white spaces and digits. I want to match the string against this pattern. Additionally I want to extract the digits (not numbers, single digits only) using std::smatch.
I tried a lot, but no success.
For the dupe hunters: I checked many many answers on SO, but I could not find a solution.
Then I tried to use the std::sregex_token_iterator
. And the result was also baffeling me. In
#include <string>
#include <regex>
#include <vector>
#include <iterator>
const std::regex re1{ R"(((?:\s*)|(\d))+)" };
const std::regex re2{ R"(\s*(\d)\s*)" };
int main() {
std::string test(" 123 45 6 ");
std::smatch sm;
bool valid1 = std::regex_match(test, sm, re1);
std::vector<std::string> v(std::sregex_token_iterator(test.begin(), test.end(), re2), {});
return 0;
}
The vector contains not only the digits, but also spaces. I would like to have digits only.
The smatch
does not contain any digits.
I know, that I can first remove all whitespaces from the string, but there should be a better, one step solution.
What is the proper regex to 1. match the string against my described pattern and 2. extract all single digits into the smatch?
\s*\d
, it will match 0+ spaces and then single digit – Michał Turczyn