29Nov/090
String matching with C++ PCRE
bool regex_match( const char *pattern, const std::string str, std::vector *substrings )
{
const char *err;
int erroffset = 0;
pcre *re = pcre_compile( pattern, 0, &err, &erroffset, NULL );
int ovector[90];
size_t rc;
if ( !re )
{
bug( "%s: regular expression compilation failed at: %d: %s", __FUNCTION__, erroffset, err );
return false;
}
if ( ( rc = pcre_exec(re, NULL, str.c_str(), str.length(), 0, 0, ovector, 90 ) ) < 0 )
switch( rc )
{
case PCRE_ERROR_NOMATCH: return false;
default: bug( "%s: Matching error: %d", __FUNCTION__, rc ); return false;
}
if ( substrings )
for ( size_t i = 0; i < rc; i++ )
substrings->push_back( str.substr( ovector[2*i], ovector[2*i+1] - ovector[2*i] ) );
return true;
}
bool simple_match( const char *pattern, const char *str )
{
std::string newPattern = "^";
for ( size_t i = 0; i < strlen(pattern); i++ )
{
if ( !isalnum( pattern[i] ) && !iscntrl(pattern[i]) )
{
if ( pattern[i] == '*' )
{
newPattern += ".*";
continue;
}
else
newPattern += '\\';
}
newPattern += pattern[i];
}
newPattern += "$";
return regex_match( newPattern.c_str(), str, NULL );
}