2010-02-23 6 views
2

정규 표현식으로 파일을 검색하고 정규식에서 찾은 내용을 삭제할 수있는 프로그램이 있습니다. 여기에 내가 작업 한 코드입니다 :정규 표현식 일치 검색 삭제

#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(); 
} 
}; 

당신은 그냥 빈 공간이 발견 된 것을 대체하는 부스트 :: regex_replace를 사용하려고했지만이 작동하지 않았다 볼 수 있듯이. 제가 실행 해본 테스트는 [*]를 사용하여리스트의 일부 이름 앞에있는 별표를 모두 찾습니다. 예 * 앨리스. 프로그램에서 별을 찾지 만 제거하지 않는 것은 앨리스에게만 적용됩니다.

+0

* 표시는 아직 그대로 일치하고있어 자신의 패턴으로 []에 있기 때문에 내가 다른 배열과 물건과 없음 작업 – shinjuo

답변

5

을하는 데 도움이됩니다. the documentation for this method을 참조하십시오.

대신을 시도해보십시오

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

+1 : OP 코드는이 방식으로 확실히 손상되었습니다. –

+0

완벽하게 작동했습니다. 그리고 그런 간단한 일. 고마워. – shinjuo

1

*를 \로 이스케이프 처리합니다.

+0

을 계속 시도. – Segfault