amxmodx/dlls/regex/CRegEx.cpp

162 lines
2.1 KiB
C++
Raw Permalink Normal View History

2004-10-05 07:17:49 +00:00
#include "pcre.h"
#include "CRegEx.h"
#include <string.h>
2004-10-05 08:13:55 +00:00
#include "amxxmodule.h"
2004-10-05 07:17:49 +00:00
RegEx::RegEx()
{
mErrorOffset = 0;
mError = NULL;
re = NULL;
mFree = true;
subject = NULL;
mSubStrings = 0;
}
void RegEx::Clear()
{
mErrorOffset = 0;
mError = NULL;
if (re)
pcre_free(re);
re = NULL;
mFree = true;
if (subject)
delete [] subject;
subject = NULL;
mSubStrings = 0;
}
RegEx::~RegEx()
{
Clear();
}
bool RegEx::isFree(bool set, bool val)
{
if (set)
{
mFree = val;
return true;
} else {
return mFree;
}
}
int RegEx::Compile(const char *pattern, const char* flags)
2004-10-05 07:17:49 +00:00
{
if (!mFree)
Clear();
int iFlags = 0;
if (flags != NULL)
{
for ( ; *flags != 0; flags++)
{
switch (*flags)
{
case 'i':
{
iFlags |= PCRE_CASELESS;
break;
}
case 'm':
{
iFlags |= PCRE_MULTILINE;
break;
}
case 's':
{
iFlags |= PCRE_DOTALL;
break;
}
case 'x':
{
iFlags |= PCRE_EXTENDED;
break;
}
default:
{
break;
}
}
}
}
re = pcre_compile(pattern, iFlags, &mError, &mErrorOffset, NULL);
2004-10-05 07:17:49 +00:00
if (re == NULL)
{
return 0;
}
mFree = false;
return 1;
}
int RegEx::Match(const char *str)
{
int rc = 0;
if (mFree || re == NULL)
return -1;
this->ClearMatch();
2004-10-05 07:17:49 +00:00
//save str
subject = new char[strlen(str)+1];
strcpy(subject, str);
rc = pcre_exec(re, NULL, subject, (int)strlen(subject), 0, 0, ovector, 30);
if (rc < 0)
{
if (rc == PCRE_ERROR_NOMATCH)
{
return 0;
} else {
mErrorOffset = rc;
return -1;
}
}
mSubStrings = rc;
return 1;
}
void RegEx::ClearMatch()
{
// Clears match results
mErrorOffset = 0;
mError = NULL;
if (subject)
delete [] subject;
subject = NULL;
mSubStrings = 0;
}
2004-10-05 07:17:49 +00:00
const char *RegEx::GetSubstring(int s, char buffer[], int max)
{
2004-10-05 08:04:13 +00:00
int i = 0;
2004-10-05 07:17:49 +00:00
if (s >= mSubStrings || s < 0)
return NULL;
char *substr_a = subject + ovector[2*s];
int substr_l = ovector[2*s+1] - ovector[2*s];
2004-10-05 08:04:13 +00:00
for (i = 0; i<substr_l; i++)
2004-10-05 07:17:49 +00:00
{
if (i >= max)
break;
buffer[i] = substr_a[i];
}
buffer[i] = '\0';
return buffer;
}