Understanding c++ regex by a simple example -
i wrote following simple example:
#include <iostream> #include <string> #include <regex> int main () { std::string str("1231"); std::regex r("^(\\d)"); std::smatch m; std::regex_search(str, m, r); for(auto v: m) std::cout << v << std::endl; }
and got confused behavior. if understood purpose of match_result
there correctly, 1 1
should have been printed. actually:
if successful, not empty , contains series of sub_match objects: first sub_match element corresponds entire match, and, if regex expression contained sub-expressions matched ([...])
the string passed function doesn't match regex, therefore should not have had the entire match
.
what did miss?
you still entire match entire match not fit entire string fits entire regex.
for example consider this:
#include <iostream> #include <string> #include <regex> int main() { std::string str("1231"); std::regex r("^(\\d)\\d"); // entire match 2 numbers std::smatch m; std::regex_search(str, m, r); for(auto v: m) std::cout << v << std::endl; }
output:
12 1
the entire match (first sub_match) entire regex matches against (part of string).
the second sub_match first (and only) capture group
looking @ original regex
std::regex r("^(\\d)"); |----| <- entire expression (sub_match #0) std::regex r("^(\\d)"); |---| <- first capture group (sub_match #1)
that 2 sub_matches come from.
Comments
Post a Comment