justinzane
justinzane

Reputation: 1987

c++ <regex> search not matching

I'm confused as to why an apparently simple RE search using c++ fails to work. The code is:

    // cliopts.infiledir.c_str() == "./samples/"
    DIR* infiledir = opendir(cliopts.infiledir.c_str());
    struct dirent* dirent = nullptr;
    std::regex infilere (".*");
    if (infiledir != nullptr) {
        while ((dirent = readdir(infiledir)) != nullptr) {
            std::string filename (dirent->d_name);
            if (std::regex_search(filename.begin(), filename.end(), infilere)){
                std::cout << "MATCH " << filename << "\n";
            } else {
                std::cout << "----- " << filename << "\n";
            }
        }
    }

and the output is:

----- .
----- ..
----- lena.jpg
----- sample0001.jpg
----- sample0002.jpg
----- sample0003.jpg
----- sample0004.jpg
----- sample0005.jpg

What will I have to dopeslap myself for not seeing?


Note that this is being built and run on Arch GNU/Linux with g++ -std=c++0x.

Upvotes: 1

Views: 242

Answers (1)

Massa
Massa

Reputation: 8972

GNU's libstdc++'s <regex> just does not work at all (until 4.9). Either install g++-4.9 or libc++ or use boost::regex... unfortunately. This program:

#include <iostream>
#include <string>
#include <regex>
#include <dirent.h>

using namespace std;

int main() {
    DIR* infiledir = opendir(".");
    struct dirent* dirent = nullptr;
    std::regex infilere (".*");
    if (infiledir != nullptr) {
        while ((dirent = readdir(infiledir)) != nullptr) {
            std::string filename (dirent->d_name);
            if (std::regex_search(filename.begin(), filename.end(), infilere)){
                std::cout << "MATCH " << filename << "\n";
            } else {
                std::cout << "----- " << filename << "\n";
            }
        }
    }
}

Its outputs:

PROMPT$  g++-4.8 -std=c++11 -o tmz tmz.cc && ./tmz
----- x.txt
----- plik1.txt~
----- tmz.cc
----- tmz
----- Makefile
----- ..
----- tmz.s
----- plik1.txt
----- .
PROMPT$  g++-4.9 -std=c++11 -o tmz tmz.cc && ./tmz                                                                                     
MATCH x.txt
MATCH plik1.txt~
MATCH tmz.cc
MATCH tmz
MATCH Makefile
MATCH ..
MATCH tmz.s
MATCH plik1.txt
MATCH .
PROMPT$  g++-libc++ -std=c++11 -o tmz tmz.cc && ./tmz
MATCH x.txt
MATCH plik1.txt~
MATCH tmz.cc
MATCH tmz
MATCH Makefile
MATCH ..
MATCH tmz.s
MATCH plik1.txt
MATCH .
PROMPT$  clang++ -std=c++11 -o tmz tmz.cc && ./tmz
MATCH x.txt
MATCH plik1.txt~
MATCH tmz.cc
MATCH tmz
MATCH Makefile
MATCH ..
MATCH tmz.s
MATCH plik1.txt
MATCH .
PROMPT$  clang++-libc++ -std=c++11 -o tmz tmz.cc && ./tmz
MATCH x.txt
MATCH plik1.txt~
MATCH tmz.cc
MATCH tmz
MATCH Makefile
MATCH ..
MATCH tmz.s
MATCH plik1.txt
MATCH .

Upvotes: 1

Related Questions