Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I modify this regex pattern?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading