regex_test.cpp -- learning boost.regex

boost.regex 库的用法,看来这可能是 boost 当中写法最“常规”的库之一了。

regex_test.cpp:

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

using namespace std;

// purpose:
// takes the contents of a file in the form of a string
// and searches for all the C++ class definitions, storing
// their locations in a map of strings/int's

typedef map<string, string::difference_type, less<string> > map_type;

const char* re =
// possibly leading whitespace:
"^[[:space:]]*"
// possible template declaration:
"(template[[:space:]]*<[^;:{]+>[[:space:]]*)?"
// class or struct:
"(class|struct)[[:space:]]*"
// leading declspec macros etc:
"("
"\\<\\w+\\>"
"("
"[[:blank:]]*\\([^)]*\\)"
")?"
"[[:space:]]*"
")*"
// the class name
"(\\<\\w*\\>)[[:space:]]*"
// template specialisation parameters
"(<[^;:{]+>)?[[:space:]]*"
// terminate in { or :
"(\\{|:[^;\\{()]*\\{)";

boost::regex expression(re);
map_type class_index;

bool regex_callback(const boost::match_results<string::const_iterator>& what)
{
// what[0] contains the whole string
// what[5] contains the class name.
// what[6] contains the template specialisation if any.
// add class name and position to map:
class_index[what[5].str() + what[6].str()] = what.position(5);
return true;
}

void load_file(string& s, istream& is)
{
s.erase();
s.reserve(is.rdbuf()->in_avail());
cout << s.capacity();
char c;
while(is.get(c))
{
if(s.capacity() == s.size())
s.reserve(s.capacity() * 3);
s.append(1, c);
}
}

int main(int argc, const char** argv)
{
string text;
for(int i = 1; i < argc; ++i)
{
cout << "Processing file " << argv[i] << endl;
ifstream fs(argv[i]);
load_file(text, fs);
// construct our iterators:
boost::sregex_iterator m1(text.begin(), text.end(), expression);
boost::sregex_iterator m2;
for_each(m1, m2, &regex_callback);
// copy results:
cout << class_index.size() << " matches found" << endl;
map_type::iterator c, d;
c = class_index.begin();
d = class_index.end();
while(c != d)
{
cout << "class \"" << (*c).first << "\" found at index: " << (*c).second << endl;
++c;
}
class_index.erase(class_index.begin(), class_index.end());
}

return 0;
}

//========== For Test =============
class Person
{};

template <class T>
class Temp
{
};

template <>
class Temp<string>
{
};

=================================================================================
cl /EHsc regex_test.cpp

regex_test regex_test.cpp

OUTPUT:

Processing file regex_test.cpp
153 matches found
class "Person" found at index: 2331
class "Temp" found at index: 2368
class "Temp<string>" found at index: 2397

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值