Regular Expression 正则表达式-4 (C++)
2004-10-04 20:58
281 查看
因为总觉得上回写的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;
}
#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;
}
相关文章推荐
- C/C++中使用正则表达式
- 利用正则表达式替换功能,将C++注释转变成纯C的注释
- C++ - 正则表达式 的 子表达式(subexpressions) 的 数据验证(data validation)
- C++正则表达式
- 正则表达式使用范例 Linux C++
- C++ regex 正则表达式 匹配IP 域名
- C++正则表达式的使用
- 转:C++深入浅出之正则表达式(二)
- (转)C/C++ 中使用正则表达式 v
- 在C/C++语言中使用正则表达式
- c++ 正则表达式邮箱
- 正则表达式使用学习(C++、Qt、Python)
- C++、Java、JavaScript中的正则表达式
- 转:C++深入浅出之正则表达式(一)
- C++ regex 正则表达式的使用
- C++ 正则表达式返回多项匹配结果
- 用C++.NET创建XML文档(用正则表达式和字符串类两种方法匹配)
- 利用正则表达式替换功能,将C++注释转变成纯C的注释
- C++正则表达式的使用
- C++学习笔记——正则表达式