编程语言

img DanceFire

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

发表于2004/10/4 20:55:00  2539人阅读

分类: 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 0

相关文章推荐

img
取 消
img