2009-04-24 5 views
3

私はウェブスパイダーを書いていて、いくつかの複雑な解析機能を作り上げるのではなく、正規表現ライブラリを使用したいと考えています。ブースト正規表現 - 一致する文字列はどこに保存されていますか?

私はこの例を見ました:

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

// 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 std::map<std::string, int, std::less<std::string> > map_type; 

boost::regex expression(
    "^(template[[:space:]]*<[^;:{]+>[[:space:]]*)?" 
    "(class|struct)[[:space:]]*" 
    "(\\<\\w+\\>([[:blank:]]*\\([^)]*\\))?" 
    "[[:space:]]*)*(\\<\\w*\\>)[[:space:]]*" 
    "(<[^;:{]+>[[:space:]]*)?(\\{|:[^;\\{()]*\\{)"); 

void IndexClasses(map_type& m, const std::string& file) 
{ 
    std::string::const_iterator start, end; 
    start = file.begin(); 
    end = file.end(); 
     boost::match_results<std::string::const_iterator> what; 
    boost::match_flag_type flags = boost::match_default; 
    while(regex_search(start, end, what, expression, flags)) 
    { 
     // 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: 
     m[std::string(what[5].first, what[5].second) 
      + std::string(what[6].first, what[6].second)] 
     = what[5].first - file.begin(); 
     // update search position: 
     start = what[0].second; 
     // update flags: 
     flags |= boost::match_prev_avail; 
     flags |= boost::match_not_bob; 
    } 
} 

をしかし、それがやや難読化されています(それはブーストと私の最初の試みです;))と私は一致する文字列の実際の場所を見つけるように見えることはできません。

私の質問は - どのようにすべてのマッチの場所を取得するのですか?

+0

zajcev、 「アポストロフィではありません」とは、後者がSOで「コード」モードに入るので、必ず使用してください。 – rlbond

答えて

5

コード内のコメントには、文字列全体が[0]で示されています。 だから、[0] .firstはループの各繰り返しで一致の先頭を指します。 と一般的には、グループi番目のあなたが使用することができます取得するには:

string s(what[i].first, what[i].second); 

このlinkをチェックし、match_resultsクラスについての詳細を読むために。

+0

私はその文字列(what [i] .first、what [i] .second)を追加して、i番目のグループの文字列を返します。 –

+0

ありがとう、編集済み、追加済み –