You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

74 lines
1.6 KiB

#include "pattern.h"
#include "cregex.h"
#include "containers/stringarray.h"
#include <proto/exec.h>
#include <stdio.h>
PATTERNPTR PatternNew(CONST_STRPTR pattern)
{
cregex_program_t* result = NULL;
cregex_node_t* patternNode = cregex_parse(pattern);
if( patternNode )
{
result = cregex_compile_node( patternNode );
if( result != NULL )
{
//Printf("successfully compiled %s\n", pattern);
}
else
{
// Printf("failed to compile %s\n", pattern);
}
cregex_parse_free( patternNode );
}
else
{
// Printf("could not parse %s\n", pattern);
}
return result;
}
VOID PatternFree(cregex_program_t* pattern)
{
cregex_compile_free( pattern );
}
StringArray PatternRun(CONST_STRPTR text, cregex_program_t* patternProgram)
{
StringArray result = NULL;
char* localMatches[] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
if (cregex_program_run(patternProgram, text, localMatches, 20) > 0) {
int j = 0;
int nmatches = 0;
// count the matches
for (j = 0; j < 20; ++j)
if (localMatches[j])
nmatches = j;
if( nmatches > 0 )
{
result = StringArrayNew();
// loop the matches
for (j = 0; j <= nmatches; j += 2) {
if (localMatches[j] && localMatches[j + 1]) {
int len = (int)(localMatches[j + 1] - localMatches[j]);
STRPTR buffer = AllocVec(len+1, MEMF_CLEAR); // freed in the array
sprintf(buffer, "%.*s", len, localMatches[j]);
if( buffer[len-1] == '\n' )
{
buffer[len-1] = '\0';
}
StringArrayAppend(result, buffer);
} else {
//Printf("(NULL,NULL)\n");
}
}
}
// end
} else {
//Printf("\"%s\": no match\n", text);
}
return result;
}