删除正则表达式匹配

问题描述:

我有一个程序,我需要能够使用正则表达式来搜索文件并删除正则表达式找到的内容。这是我一直在努力代码:删除正则表达式匹配

#include <boost/regex.hpp> 
#include <iostream> 
#include <string> 
#include <fstream> 
#include <sstream> 
#include "time.h" 
using namespace std; 


class application{ 
private: 
//Variables 
boost::regex expression; 
boost::smatch matches; 
string line; 
string pat; 
int lineNumber; 
string replace; 
char time[9]; 
char date[9]; 

//Functions 
void getExpression(){ 
    cout << "Expression: "; 
    cin >> pat; 
    try{ 
    expression = pat; 
    } 
    catch(boost::bad_expression){ 
    cout << pat << " is not a valid regular expression\n"; 
    exit(1); 
    } 
} 

void boostMatch(){ 
    //Files to open 
    //Input Files 
    ifstream in("files/trff292010.csv"); 
    if(!in) cerr << "no file\n"; 
    //Output Files 
    ofstream out("files/ORIGtrff292010.csv"); 
    ofstream newFile("files/NEWtrff292010.csv"); 
    ofstream record("files/record.dat"); 
    //time 
    _strdate_s(date); 
    _strtime_s(time); 
    lineNumber = 0; 

    while(in.peek() != EOF){ 
    getline(in, line, '\n'); 
    lineNumber++; 
    out << line << "\n"; 
    if (regex_search(line, matches, expression)){ 
    for (int i = 0; i<matches.size(); ++i){ 

    record << "Date: "<< date << "Time: " << time << "\tmatches[" << i << "]: " << matches[i] << "\n\tLine Number: "<< lineNumber<< '\n\t\t' << line << '\n'; 
    boost::regex_replace(line, expression, ""); 
    newFile << line << "\n"; 
    } 
    }else{ 
    newFile << line << "\n"; 
    } 
    } 
} 

public: 
void run(){ 
    replace = ""; 
    getExpression(); 
    boostMatch(); 
} 
}; 

正如你看到的我是想使用boost :: regex_replace只需更换什么发现有空格,但没有奏效。我一直在运行的测试是使用[*]查找列表中某些名称前的所有星号。示例*爱丽丝。该程序确实找到了明星,但并没有删除只是爱丽丝

+0

我不断尝试不同的安排和的东西,没有工作 – shinjuo 2010-02-24 01:03:15

看起来的boost :: regex_replace返回一个字符串,而不是修改输入。见the documentation for this method

试试这个:

newFile << boost::regex_replace(line, expression, "") << "\n"; 
+0

+1:OP代码肯定是以这种方式破坏的。 – 2010-02-26 20:05:01

+0

完美运作。而这样一件简单的事情。非常感谢 – shinjuo 2010-03-01 05:42:19

逃脱与* \ *。

+0

因为*是[]在他的模式,它已经被逐字匹配。 – Segfault 2010-02-26 19:59:22

这是一个相当普遍的问题, http://bytes.com/topic/c/answers/166133-problem-boost-regex_replace

也许上面的链接有助于