Search code examples
c++regexc++11boostboost-regex

Unable to find matches using Boost RegEx


I am using boost 1.67.0 regex to find matching filenames in current folder using following snippet

boost::filesystem::path p(".");
if(is_directory(p)) {

    for(auto& entry : boost::make_iterator_range(boost::filesystem::directory_iterator(p), {})){
        std::stringstream ss;
        ss << entry;
        std::string filename = ss.str();
        std::cout << filename << std::endl;
        boost::regex pattern("some_\\d+_file\.txt");

        if(boost::regex_match(filename, pattern)){
            std::cout << "matched" << filename << std::endl;
        }            
    }   
}

Contents of current directory, produced by std::cout << filename << std::endl; line, are:

"./myApp.out"
"./some_0_file.txt"
"./some_1_file.txt"
"./other_file.txt"
"./some_other_file.txt"
"./some_2_file.txt"

To confirm that my matching expression is correct I consulted Perl Regular Expression Syntax. Also confirmed it using RegEx101.com, output correctly shows 3 matches as follows:

some_0_file.txt
some_1_file.txt
some_2.file.txt

Question

Is there anything wrong with my snippet or RegEx? Why boost::regex_match produce 0 match?

What have I missed?


Solution

  • boost::filesystem::path p(".");
    if (is_directory(p)) {
    
        for (auto& entry : boost::make_iterator_range(boost::filesystem::directory_iterator(p), {})) {
            std::stringstream ss;
            ss << entry.path().string(); //2
            std::string filename = ss.str();
            std::cout << filename << std::endl;
            boost::regex pattern(".*some_\\d+_file\\.txt"); //1
            if (boost::regex_match(filename, pattern)) {
                std::cout << "matched" << filename << std::endl;
            }
        }
    }
    

    1.regex_match only consider a full match

    2.operator<<(std::basic_ostream<Char, Traits>& os, const path& p) will use boost::io::quoted() and add quotes to handle spaces in paths