Tuesday, August 29, 2017

C++11: Regex: Grep

You can use the regex facilities like grep. Here is an example:

#include <fstream>
#include <iostream>
#include <regex>
#include <string>

int main(int argc, char * argv[])
{
  if (argc != 3)
  {
    std::cerr << "Usage: grep <regex> <filename>" << std::endl;
    exit(1);
  }

  std::string   myString;
  std::smatch   myMatches;
  std::regex    myRegex(argv[1]);
  std::ifstream ifs(argv[2]);

  if (ifs.is_open())
  {
    while (std::getline(ifs, myString))
    {
      std::regex_search(myString, myMatches, myRegex);
      if (myMatches.size() == 1)
      {
        std::cout << myString << std::endl;
      }
    }
  }
  else
  {
    std::cout << "Unable to open file." << std::endl;
  }
  return 0;
}
/* Input:
     grep abc test.txt

   test.txt:
     abc
     def
     defabc
     hij
   
   Output:
    abc
    defabc
*/
Reference: http://www.cplusplus.com/reference/regex/regex_search/

No comments:

Post a Comment