I am working on PCRE for the first time . my code needs to find the @ refernce as u would see in twitter and remove it. knowing that pcre library has no replace function . i wrote myself . it works fine when i use the function once . but iterating again corrupts my string .
Any idea
Code:
#include <stdio.h>
#include <string.h>
#include <regex.h>
#include <pcre.h>
char* sanitize(char*);
char* stringReplace(char* subj,int start,int end,char* replace);
char* pcreReplace(char* regex,char* txt);
int main()
{
char* str="a ina @abcds http://aa.com @abcds ";
str=sanitize(str);
//printf("%s\n",str);
return 0;
}
char* sanitize(char* str)
{
//remove @ reference
str=pcreReplace("@([^\\s]){1,}",str);
str=pcreReplace("@([^\\s]){1,}",str);
//str=pcreReplace("https?([^\\s]){1,}",str);
return str;
}
char* pcreReplace(char* re,char* txt)
{
const char *error;
int erroffset;
int ovector[186];
pcre *r = pcre_compile(re, PCRE_CASELESS|PCRE_DOTALL, &error, &erroffset, NULL);
int rc = pcre_exec(r, NULL, txt, strlen(txt), 0, 0, ovector, 186);
printf("%s\n",txt);
if(rc<0)
return txt;
//printf("%i",ovector[0]);
//char c1[1024];
//pcre_copy_substring(txt, ovector, rc,1,c1, 1024);
txt=stringReplace(txt,ovector[0],ovector[2],"");
return txt;
}
char* stringReplace(char* subj,int start,int end,char* replace)
{
int newLength=strlen(subj)-(end-start+1)+strlen(replace);
char newString[newLength];
int i;
int itr=0;
for(i=0;i<strlen(subj);i++)
{
if(i<start || i>end)
{
newString[itr]=subj[i];
itr++;
}
}
newString[newLength]='\0';
return newString;
}