|
Boost : |
From: John Maddock (John_Maddock_at_[hidden])
Date: 2001-04-30 06:34:02
>I expect matches[1].first to return "Moose", the first match. But it
>doesn't - it returns "Moose, Orangutang". matches[2].first returns
>"Orangutang", which makes some sense.
>
>Actually, I don't understand this whole first/second business in
>sub_matches. In any other language, matches[0] would just be a string
>or something. But here, obviously things are being done differently,
>and just don't understand what the scheme is here. I've read the docs
>over and over, and I can't find a darn thing.
The regex library is iterator based (just like the standard library
algorithms are), so when you locate a match what you get back is a pair of
*iterators* denoting the start and end of the match, and a bool flag
indicating whether that sub-expression particiapated in the match (in some
expression/text combinations some sub-expressions may be unmatched). So
the docs define sub_match as:
template <class iterator>
struct sub_match
{
typedef typename std::iterator_traits<iterator>::value_type
value_type;
typedef typename std::iterator_traits<iterator>::difference_type
difference_type;
typedef iterator
iterator_type;
iterator first;
iterator second;
bool matched;
operator std::basic_string<value_type>()const;
bool operator==(const sub_match& that)const;
bool operator !=(const sub_match& that)const;
difference_type length()const;
};
It really is just a simple structure, with the range [first,second)
denoting what matched.
You can also cast the result to the string, either explicitly or
implicitly:
#include <iostream>
#include <boost\regex.hpp>
using namespace boost;
using namespace std;
int main(int argc, char* argv[])
{
regex rxHeader("(\\w+), (\\w+)");
cmatch matches;
if (regex_match("Moose, Orangutang", matches, rxHeader))
{
// explict cast:
cout << static_cast<std::string>(matches[1]) << endl;
// implicit cast:
std::string s = matches[2];
cout << s << endl;
}
else
puts("No match.");
return 0;
}
- John Maddock
http://ourworld.compuserve.com/homepages/john_maddock/
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk