Regular Expression 正则表达式-3 (C++)

最后用C++实现了一把,因为STL中尚未包含Regular Expression,因此我使用了Boost中的Regex++。不过因为不是很熟悉,所以代码很蹩脚,将就看了。呵呵。

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

using namespace std;

void readFile( const char* filename, string& str );
void writeFile( const char* filename, const string str );
void filter( const string input, string& output );

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

    
readFile( argv[1], strIn );
    
filter( strIn, strOut );
    
writeFile( argv[2], strOut );
}

void readFile( const char* filename, string& str )
{
    
ifstream in( filename );
    
str.erase();
    
str.reserve( in.rdbuf()->in_avail() );
    
string strTemp;
    while( !
in.eof() )
    {
        
in >> strTemp;
        
str.append(strTemp);
    }
    
in.close();
}

void writeFile( const char* filename, const string str )
{
    
ofstream out( filename );
    
out.write( str.c_str(), (streamsize)str.length() );
    
out.flush();
    
out.close();
}
void filter( const string input, string& output )
{
    
output.erase();
    
output.reserve( input.length() );

    
boost::regex expression("/"(//w+):(//w+)%(//w+)/"");
    
boost::smatch group;
    
boost::regex_constants::match_flag_type flags = boost::regex_constants::match_default;

    
string::const_iterator start, end;
    
start = input.begin();
    
end = input.end();

    while(
boost::regex_search( start, end, group, expression, flags ))
    {
        
output.append( group[1] );
        
output.append( ":" );
        
output.append( group[2] );
        
output.append( "*" );
        
output.append( group[3] );
        
output.append( "," );
        
output.append( "/n" );
        
// update
        
start = group[0].second;
        
flags |= boost::regex_constants::match_prev_avail;
        
flags |= boost::regex_constants::match_not_bob;
    }
    return;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值