[英]Create a single regular expression instead of multiple expression
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. 这使得后半部分为可选的(以便“ 2”仍然匹配),并使后半部分的* 0位为可选。
The $
at the end is necessary so that if the string does contain the optional parts then they will definitely still be matched & captured. 最后的
$
是必需的,因此,如果字符串确实包含可选部分,则它们肯定仍会被匹配和捕获。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.