I want to find log files ending with "access" and a number, such as 500m-access0.log.
My code :
bool is_access_log(const char *file_name)
{
std::string name(file_name);
struct stat file_info;
if (stat(file_name, &file_info) < 0 || S_ISDIR((&file_info)->st_mode))
{
// return false if dir
return false;
}
std::regex reg("(.)(-access)(\\d).log");
return std::regex_match(file_name, reg);
}
but I got false when I use 500m-access0.log and any_name-access3.log
>Solution :
std::regex_match matches the given regex against the entire string.
You can use std::regex_search instead to match the regex against any part of the string:
std::regex reg(R"(-access\d\.log$)");
return std::regex_search(file_name, reg);
Note that you should escape . to match a literal ., and use $ to anchor the end of a string. There’s also no need to use capture groups since you aren’t using them.