这是上一个SO问题及其讨论的延续。
std :: regex_match和std :: regex_search之间的区别
在我的SO问题中,编写了以下正则表达式以从给定的输入字符串中获取日期:
std::string input{ "Mon Nov 25 20:54:36 2013" };
//Day:: Exactly Two Number surrounded by spaces in both side
std::regex r{R"(\s\d{2}\s)"};
在一个答案中,它被更改为R"(.*?\s(\d{2})\s.*)"
创建并因此捕获组和第一个子匹配。一切都可以使用regex_match
或解析日期信息regex_search
。
现在,我编写了以下代码,regex expressions
以解析上述输入字符串中的各种内容,如下所示:
std::string input{ "Mon Nov 25 20:54:36 2013" };
//DayStr:: Exactly Three Letter at the start and followed by spaces(Output: Mon)
std::regex dayStrPattern{ R"(^\w{3}\s)" };
//Day:: Exactly Two Number surrounded by spaces in both side(Output: 25)
std::regex dayPattern{ R"(\s\d{2}\s)" };
//Month:: Exactly Three letter surrounded by spaces in both side(Output: Nov)
std::regex monthPattern{ R"(\s\w{3}\s)" };
//Year:: Exactly Four Number at the end of the string(Output: 2013)
std::regex yearPattern{ R"(\s\d{4}$)" };
//Hour:: Exactly two Number surrounded by spaces in left side and : in right side(Output:20)
std::regex hourPattern{ R"(\s\d{2}:{1})" };
//Min:: Exactly two Number sorruounded by : in left side and : in right side(Output: 54)
std::regex minPattern{ R"(:{1}\d{2}:{1})" };
//Second::Exactly two Number surrounded by : in the left side and space in right side(Output: 36)
std::regex secPattern{ R"(:{1}\d{2}\s)" };
我在这里测试了上述正则表达式,它们似乎是正确的。
现在我们可以在这里使用分组机制了,以便我们在方法中传递单个regex表达式,std::regex_search
而不是7个不同的regex。?。这样std :: regex_search会将输出存储到其std::smatch
子匹配向量中。有可能在这里吗?我读了documentation
A,Tour Of C++ book
但是对A的了解却很少regular expression grouping
。
通常,何时以及如何使用/设计分组,以便一次调用std :: regex_search就能获得各种信息?
此时,我必须使用不同的regex表达式调用7次std :: regex_search来获取各种信息,然后使用它。我可以肯定地说,有一种比我现在正在做的更好的方法来实现它。
无需调用regex_match
7次以匹配同一输入的7个部分,只需创建多个捕获组即可,而不是每次都创建一个捕获组。例如,将您更改regex
为
std::regex r{R"(^(\w{3}) (\w{3}) (\d{2}) (\d{2}):(\d{2}):(\d{2}) (\d{4})$)"};
然后,只需match_results
调用一次,就可以获取所有匹配项regex_match
if (std::regex_match(input,match,r)){
for(auto const& m : match) {
std::cout << m << '\n';
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句