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 
- #include <iostream> 
 
- #include <string> 
 
- using namespace std; 
 
- #include "my_regexp.h"
 
- //g++ -g -std=c++0x main.cpp my_regexp.cpp
 
- int main() {
 
-   string s0("Tin 454 s1");
 
-   string r("\\(T.*\\) [0-9]* \\(.*\\)/\\1 \\2");
 
-   string s1;
 
-   s1 = reg_replace(s0, r);
 
-   cout << s0 << " " << r << endl;
 
-   cout << s1 << endl;
 
-   return 0;
 
- }
 
 
 
my_regexp.cpp 
- #include <iostream> 
 
- #include <string> 
 
- using namespace std; 
 
- string reg_replace(string& str, string& sed) {
 
-   string cmd("echo "); 
 
-   cmd = cmd + "\"" + str + "\" | sed 's/" + sed + "/'";
 
-   FILE* pfd = popen(cmd.c_str(), "r"); 
 
-    
 
-   if (pfd) 
 
-   { 
 
-     while (!feof(pfd)) 
 
-     { 
 
-       char buf[1024] = {0}; 
 
-        
 
-       if (fgets(buf, sizeof(buf), pfd) > 0) 
 
-         return buf;
 
-     } 
 
-     pclose(pfd); 
 
-   } 
 
- }
 
 
my_regexp.h
  
string reg_replace(string& str, string& sed); 
 
  
The output looks like:
  
- ./a.out 
  
- Tin 454 s1 \(T.*\) [0-9]* \(.*\)/\1 \2
  
- Tin s1
  
 
Similar links: 
c++ exercise, which uses boost to implement regular expression replace.
  
                           |