且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

std::regex_match & 之间的区别std::regex_search?

更新时间:2023-02-20 08:42:11

regex_match 仅在整个输入序列匹配时返回 true,而 regex_searchregex 匹配,/code> 也会成功.

regex_match only returns true when the entire input sequence has been matched, while regex_search will succeed even if only a sub-sequence matches the regex.

引自 N3337,

§28.11.2/2 regex_match [re.alg.match]

作用:判断正则表达式e所有的字符序列[first,last)强>.... 如果存在这样的匹配,则返回 true,否则返回 false.

§28.11.2/2 regex_match [re.alg.match]

Effects: Determines whether there is a match between the regular expression e, and all of the character sequence [first,last). ... Returns true if such a match exists, false otherwise.

以上描述是针对regex_match 重载的,它采用一对迭代器到要匹配的序列.其余的重载是根据这个重载定义的.

The above description is for the regex_match overload that takes a pair of iterators to the sequence to be matched. The remaining overloads are defined in terms of this overload.

对应的regex_search重载描述为

§28.11.3/2 regex_search [re.alg.search]

Effects: 判断[first,last)中是否存在与正则表达式e匹配的某个子序列.... 如果存在这样的序列,则返回 true,否则返回 false.

§28.11.3/2 regex_search [re.alg.search]

Effects: Determines whether there is some sub-sequence within [first,last) that matches the regular expression e. ... Returns true if such a sequence exists, false otherwise.

在您的示例中,如果您将 regex 修改为 r{R"(.*?sd{2}s.*)"};regex_matchregex_search 都会成功(但匹配结果不仅仅是日期,而是整个日期字符串).


In your example, if you modify the regex to r{R"(.*?sd{2}s.*)"}; both regex_match and regex_search will succeed (but the match result is not just the day, but the entire date string).

现场演示 示例的修改版本,其中 regex_matchregex_search.

Live demo of a modified version of your example where the day is being captured and displayed by both regex_match and regex_search.