我有一个程序,我需要能够使用正则表达式搜索文件搜索并删除正则表达式找到的内容。这是我一直在研究的代码:
#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来替换用空格找到的内容,但这不起作用。我一直在运行的测试是使用[*]查找列表中某些名称之前的所有星号。示例* alice。该程序确实找到明星,但不删除只是alice
答案 0 :(得分:5)
似乎boost :: regex_replace返回一个字符串而不是修改输入。请参阅the documentation for this method。
请改为尝试:
newFile << boost::regex_replace(line, expression, "") << "\n";
答案 1 :(得分:1)
以\。
逃离*答案 2 :(得分:1)
这是一个相当普遍的问题, http://bytes.com/topic/c/answers/166133-problem-boost-regex_replace
也许以上链接有帮助