Trevor Hickey Trevor Hickey - 3 years ago 121
C++ Question

Why doesn't std::regex_match return true with $ pattern?

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.


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';

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download