With std::regex_replace,
I can match the end of a word using "$" and then append additional characters.
std::cout << std::regex_replace("word",std::regex("$"),"s") << '\n';
//prints: words
Since the result was different than the original input, I assumed the regular expression had matched.
However,
std::cout << std::boolalpha;
std::cout << std::regex_match("word",std::regex("$")) << '\n';
//prints: false
How can it be that the regular expression does not match, yet regex_replace was able to make a replacement?
I also tried adding a *
for 0 or more characters, but that threw an exception:
std::cout << std::regex_match("word",std::regex("*$")) << '\n';
std::cout << std::regex_replace("word",std::regex("*$"),"s") << '\n';
Note that regex_match will only successfully match a regular expression to an entire character sequence, whereas std::regex_search will successfully match subsequences.
You want regex_search
for matching subsequences. $
does not match the entirety of a non-empty string, but does match a (zero-length) substring of a non-empty string.