0

I want to search a file with a regex and the result should be ALL matched strings.

I have already written the regex for command line execution but I need this implemented in C++:

grep -E -o "\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,6}\b" filename.txt

Can I do this with the regex_search function?

According to this example here the method takes a string as input. Do I have to open it and read it in line by line myself, or is there probably a way to give the file as parameter and just get the results as return?

EDIT I implemented the regular expression search now, but I don't get the results as expected.

void readFile(fs::path filename) {
    ifstream in(filename.string(), ios::in | ios::binary);

    if (in) {
        string content;
        in.seekg(0, ios::end);
        content.resize(in.tellg());
        in.seekg(0, ios::beg);
        in.read(&content[0], content.size());
        in.close();

        searchContent(content);
    }

}

void searchContent(string content) {
     smatch match;
     regex expr("\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,6}");

     while (regex_search(content, match, expr)) {
          for (auto x : match)
               cout << x << " ";

           cout << std::endl;
           content = match.suffix().str();
     }

}

My test file has the following content:

  abc@gmail.com xxx
  xxx xx test@yahoo.com xxx
  sss a@a.to

But the output I get from the program is

   abc@gmail.com xxx 
   test@yahoo.com xxx 
   a@a.to 

The last xxx should not be printed!?

wasp256
  • 5,355
  • 9
  • 53
  • 94

0 Answers0