Boost logo

Boost Users :

From: John Maddock (john_at_[hidden])
Date: 2006-07-13 12:20:46


Line Oddskool wrote:
> John Maddock wrote:
>> The way to find out which sub-expression matched is simply:
>>
>> match_results<something> what;
>> ...
>> for(unsigned i = 1; i < what.size(); ++i)
>> {
>> if(what[i].matched)
>> std:cout << "sub-expression " << i << " matched " << what[i] <<
>> std::endl;
>> }
>
> First, thanks for the reply, it's nearly what I need ;)
>
> Actually, either I misunderstood something or is this code giving me
> just the first part in the regex that matches ?
>
> e.g. if I try
>
> <code>
>
> std::string myString ="jayjay";
> std::string myRegexSearch = "(ay)|(j)(?=[aeiouy])";
>
> boost:regex* myRegexp = new boost::regex (myRegexSearch,
> boost::regex::normal);
>
> boost::cmatch what;
>
> boost::regex_search (myString , what, *myRegexp);
>
> for(unsigned _ = 1; _ < what.size(); ++_)
> {
> if(what[_].matched)
> printf("rule [%d] matched '%s'\n",_,what[_]);
> }
> delete myRegexp;
>
> </code>
>
> The output is
>
> rule [2] matched 'jayjay'
>
> where I expected it to tell me "rule 1" and "rule 2" matched!
>
> Am I missing something?

Well I'm amazed your computer didn't explode in a ball of flame when you
passed a structure (boost::sub_match) by value to printf :-) Hint:
match_results::operator[] does *not* return a null-terminated string.

But apart from that if you want to search through all the occurances of the
expression in the text, then use regex_iterator:

std::string mystring = whatever;
boost::regex e(myregex);

boost::sregex_iterator i(e, mystring.begin(), mystring.end()), j;

while(i != j)
{
 for(unsigned sub = 1; sub < what.size(); ++sub)
 {
   if((*i)[sub].matched)
      std::cout << (*i)[sub] << std::endl;
 }
}

HTH, John.


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net