00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030
00031 #include <sys/types.h>
00032 #include <string.h>
00033 #include <regex.h>
00034 #include <ctype.h>
00035 #include "regexp.h"
00036 #include "dprint.h"
00037
00038
00039
00040
00041 int replace(regmatch_t* pmatch, char* string, char* replacement, str* result)
00042 {
00043 int len, i, j, digit, size;
00044
00045 len = strlen(replacement);
00046 j = 0;
00047
00048 for (i = 0; i < len; i++) {
00049 if (replacement[i] == '\\') {
00050 if (i < len - 1) {
00051 if (isdigit((unsigned char)replacement[i+1])) {
00052 digit = replacement[i+1] - '0';
00053 if (pmatch[digit].rm_so != -1) {
00054 size = pmatch[digit].rm_eo - pmatch[digit].rm_so;
00055 if (j + size < result->len) {
00056 memcpy(&(result->s[j]), string+pmatch[digit].rm_so, size);
00057 j = j + size;
00058 } else {
00059 return -1;
00060 }
00061 } else {
00062 return -2;
00063 }
00064 i = i + 1;
00065 continue;
00066 } else {
00067 i = i + 1;
00068 }
00069 } else {
00070 return -3;
00071 }
00072 }
00073 if (j + 1 < result->len) {
00074 result->s[j] = replacement[i];
00075 j = j + 1;
00076 } else {
00077 return -4;
00078 }
00079 }
00080 result->len = j;
00081 return 1;
00082 }
00083
00084
00085
00086 int reg_match(char *pattern, char *string, regmatch_t *pmatch)
00087 {
00088 regex_t preg;
00089
00090 if (regcomp(&preg, pattern, REG_EXTENDED | REG_NEWLINE)) {
00091 return -1;
00092 }
00093 if (preg.re_nsub > MAX_MATCH) {
00094 regfree(&preg);
00095 return -2;
00096 }
00097 if (regexec(&preg, string, MAX_MATCH, pmatch, 0)) {
00098 regfree(&preg);
00099 return -3;
00100 }
00101 regfree(&preg);
00102 return 0;
00103 }
00104
00105
00106
00107
00108
00109 int reg_replace(char *pattern, char *replacement, char *string, str *result)
00110 {
00111 regmatch_t pmatch[MAX_MATCH];
00112
00113 LM_DBG("pattern: '%s', replacement: '%s', string: '%s'\n",
00114 pattern, replacement, string);
00115
00116 if (reg_match(pattern, string, &(pmatch[0]))) {
00117 return -1;
00118 }
00119
00120 return replace(&pmatch[0], string, replacement, result);
00121
00122 }