Regular Expression 正則表達式-4 (C++)

因爲總覺得上回寫的C++代碼太過蹩腳了,心有不甘。畢竟C++是一個很優秀的語言,並且有着衆多出色的模板庫,這麼簡單的一個小程序被我給用成那樣,真的是太慚愧了。代碼絕對不應該這麼臃腫。實際上我有幾個概念模糊不清了,所以導致了代碼的臃腫,一個是輸入輸出流的概念模糊了,還有一個是正則表達式應用不熟悉。於是重溫了輸入輸出流,並且詳細的閱讀了正則表達式的Boost庫的說明文檔。新寫的代碼如下,明顯比原來的代碼優雅了許多:

#include <string>
#include <boost/regex.hpp>
#include <iostream>
#include <fstream>
#include <sstream>

using namespace std;
using namespace boost;

string filter
( const string in )
{
    
regex expr("/"(//w+):(//w+)%(//w+)/"");
    
string fmt("$1:$2*$3,/n");
    
ostringstream ostring;
    
ostream_iterator<char> oi(ostring);

    
regex_replace( oi, in.begin(), in.end(), expr, fmt, (match_default | format_no_copy) );

    return
ostring.str();
}

int main
(int argc, const char* argv[])
{
    if(
argc < 3 )
    {
        
cout<< "Please enter 2 filenames(e.g. In.txt Out.txt)" << endl;
        return
1;
    }

    
ifstream in( argv[1] );
    
ofstream out( argv[2] );
    
ostringstream buf;

    
buf << in.rdbuf();
    
out << filter( buf.str() ) << flush;
}

發佈了42 篇原創文章 · 獲贊 3 · 訪問量 41萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章