Intermediate Gotchas
The Search That Accepted a Suffix
a validator that finds a number inside anything
int main() {
const std::regex whole_number{"[0-9]+"};
const std::string input = "42ms";
std::cout << std::boolalpha << std::regex_search(input, whole_number) << '\n';
}
Does the number-only pattern reject "42ms"?
Why¶
std::regex_search succeeds when any subsequence matches the expression. The digits
at the front satisfy [0-9]+, leaving the ms suffix irrelevant. std::regex_match
instead requires the entire character sequence to match, which is the usual rule for
validation. GCC 11.5 emits no warning under -Wall -Wextra because both calls are valid.
The fix¶
Takeaway: use regex_match for whole-input validation and regex_search only when
finding a matching part is the point.
Try it: g++ -std=c++17 main.cpp -o demo && ./demo