Matching and searching
To ask whether a given input string haystack
conforms to a given regex rneedle
, you can use std::regex_match(haystack, rneedle)
. The regex always comes last, which is reminiscent of JavaScript's syntax haystack.match(rneedle)
and Perl's haystack =~ rneedle
even as it's opposed to Python's re.match(rneedle, haystack)
. The regex_match
function returns true
if the regex matches the entire input string, and false
otherwise:
std::regex rx("(left|right) ([0-9]+)"); std::string line; while (std::getline(std::cin, line)) { if (std::regex_match(line, rx)) { process_command(line); } else { printf("Unrecognized command '%s'.\n", line.c_str()); } }
The regex_search
function returns true
if the regex matches any portion of the input string. Essentially, it just puts .*
on both sides of the regex you provided and then runs the regex_match
algorithm; but implementations can generally perform a regex_search
faster than they...