Boost Regex - Где хранятся соответствующие строки? - PullRequest
3 голосов
/ 24 апреля 2009

Я пишу веб-паук и хочу использовать библиотеку регулярных выражений boost вместо создания некоторых сложных функций синтаксического анализа.

Я взглянул на этот пример:

#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; 
   } 
}

но, он несколько запутан (это моя первая попытка с boost;)), и я не могу найти фактическое расположение соответствующих строк.

Итак, мой вопрос - как мне узнать местоположение всех совпадений?

1 Ответ

5 голосов
/ 24 апреля 2009

Как показывают комментарии в коде, то, что [0] содержит всю строку. так что [0] .first будет указывать на начало совпадения на каждой итерации цикла. и вообще, чтобы получить i-ю группу, вы можете использовать:

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

чтобы узнать больше о классе match_results, проверьте эту ссылку .

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...