Monday, September 7, 2009

Use regular expression in your C++ program (vbscript and groups)

There's a great tutorial how to reuse VB6 regular expressions in C++ on sourceforge and here's how to use it in more depth. Unfortunately there are not many examples how to use it in C++ and figuring out how to access groups was not hard, just took a while. The key is to use the version 2 of all the classes, starting with IRegExp2Ptr. So just an example how to do it:

IRegExp2Ptr regExp;
regExp.CreateInstance(__uuidof(RegExp));
regExp->Pattern = _bstr_t("^(\\d+)-(..)-(.*)\\.44$");

if (regExp->Test("11-ab-33.44") == VBOOL_TRUE)
{
IMatchCollection2Ptr matches = regExp->Execute("11-ab-33.44");
IMatch2Ptr match = matches->Item[0];
ISubMatchesPtr sbm = match->GetSubMatches();
_bstr_t val = _bstr_t(sbm->Item[0]); //11
_bstr_t val = _bstr_t(sbm->Item[1]); //ab
_bstr_t val = _bstr_t(sbm->Item[2]); //33
}

No comments: