Email: bknpk@hotmail.com Phone: +972-54-7649119


V

 

Simple c++ exercise which runs sed command from c++ program. The sed is done in a separate routine. The routine is called with string and sed parameters.

main.cpp
  1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4. #include "my_regexp.h"
  5. //g++ -g -std=c++0x main.cpp my_regexp.cpp
  6. int main() {
  7.   string s0("Tin 454 s1");
  8.   string r("\\(T.*\\) [0-9]* \\(.*\\)/\\1 \\2");
  9.   string s1;
  10.   s1 = reg_replace(s0, r);
  11.   cout << s0 << " " << r << endl;
  12.   cout << s1 << endl;
  13.   return 0;
  14. }

my_regexp.cpp
  1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4. string reg_replace(string& str, string& sed) {
  5.   string cmd("echo ");
  6.   cmd = cmd + "\"" + str + "\" | sed 's/" + sed + "/'";
  7.   FILE* pfd = popen(cmd.c_str(), "r");
  8.   
  9.   if (pfd)
  10.   {
  11.     while (!feof(pfd))
  12.     {
  13.       char buf[1024] = {0};
  14.       
  15.       if (fgets(buf, sizeof(buf), pfd) > 0)
  16.        return buf;
  17.     }
  18.     pclose(pfd);
  19.   }
  20. }
my_regexp.h

string reg_replace(string& str, string& sed);



The output looks like:

  1. ./a.out
  2. Tin 454 s1 \(T.*\) [0-9]* \(.*\)/\1 \2
  3. Tin s1
Similar links:
c++ exercise, which uses boost to implement regular expression replace.


  ...


Search This Site


Feedback This Site




new pages on this site