Im trying create a regular expresion which matches strings pushed onto the strings vector. Is it possible to create a single regular expression to match and extract all the "numerical" values?
std::vector<std::string> strings;
strings.push_back("100/2");
strings.push_back("2");
strings.push_back("200/99");
strings.push_back("150/9*0");
std::regex rex1("(\\d{1,3})(\\/(\\d{1,2})(\\*(\\d+)))"); // matches 150/9*0
std::regex rex2("(\\d{1,3})(\\/(\\d{1,2}))"); // matches 200/99
for (size_t k = 0; k < strings.size(); k++)
{
std::smatch m;
std::regex_match(strings[k], m, rex1);
for (size_t i = 0; i < m.size(); i++)
std::cout << "match " << i << ": " << m[i] << std::endl;
}
^(\\d{1,3})(\\/(\\d{1,2})(\\*(\\d+))?)?$
That makes the second half optional (so that the "2" still matches) and makes the *0 bit optional within the second half.
The $
at the end is necessary so that if the string does contain the optional parts then they will definitely still be matched & captured.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.