gpt4 book ai didi

c++ - 删除正则表达式匹配

转载 作者:搜寻专家 更新时间:2023-10-31 00:05:27 24 4
gpt4 key购买 nike

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

#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 将找到的内容替换为空格,但这不起作用。我一直在运行的测试是使用 [*] 来查找列表中某些名称之前的所有星号。例如*爱丽丝。该程序确实找到了星星但没有删除只是爱丽丝

最佳答案

似乎 boost::regex_replace 正在返回一个字符串而不是修改输入。参见 the documentation for this method .

试试这个:

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

关于c++ - 删除正则表达式匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2319334/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com