3 /* This file contains the regsub() function, which performs substitutions
4 * after a regexp match has been found.
13 /* perform substitutions after a regexp match */
14 void regsub(re
, src
, dst
)
15 regexp
*re
; /* the regexp with pointers into matched text */
16 REG
char *src
; /* the replacement string */
17 REG
char *dst
; /* where to put the result of the subst */
19 REG
char *cpy
; /* pointer to start of text to copy */
20 REG
char *end
; /* pointer to end of text to copy */
24 int mod
= 0;/* used to track \U, \L, \u, \l, and \E */
25 int len
; /* used to calculate length of subst string */
26 static char *prev
; /* a copy of the text from the previous subst */
28 /* replace \~ (or maybe ~) by previous substitution text */
30 /* step 1: calculate the length of the new substitution text */
31 for (len
= strlen(src
), c
= '\0', cpy
= src
; *cpy
; cpy
++)
34 if (c
== '\\' && *cpy
== '~')
36 if (c
== (*o_magic
? '\0' : '\\') && *cpy
== '~')
41 regerror("No prev text to substitute for ~");
44 len
+= strlen(prev
) - 1;
48 len
-= 1; /* because we lose the \ too */
51 /* watch backslash quoting */
52 if (c
!= '\\' && *cpy
== '\\')
58 /* allocate memory for the ~ed version of src */
59 start
= cpy
= (char *)malloc((unsigned)(len
+ 1));
62 regerror("Not enough memory for ~ expansion");
66 /* copy src into start, replacing the ~s by the previous text */
70 if (*o_magic
&& *src
== '~')
76 else if (!*o_magic
&& *src
== '\\' && *(src
+ 1) == '~')
78 if (*src
== '\\' && *(src
+ 1) == '~')
79 # endif /* NO_MAGIC */
92 if ((int)(cpy
- start
) != len
)
94 msg("Bug in regsub.c! Predicted length = %d, Actual length = %d", len
, (int)(cpy
- start
));
98 /* remember this as the "previous" for next time */
103 #endif /* undef CRUNCH */
106 while ((c
= *src
++) != '\0')
109 /* recognize any meta characters */
110 if (c
== '&' && *o_magic
)
116 #endif /* not NO_MAGIC */
133 /* \0 thru \9 mean "copy subexpression" */
143 /* \U and \L mean "convert to upper/lowercase" */
149 /* \E ends the \U or \L */
152 # endif /* not CRUNCH */
154 /* "\&" means "original text" */
166 /* "\&" means "original text" */
170 #endif /* NO_MAGIC */
172 /* ordinary char preceded by backslash */
184 /* transliterate ^M into newline */
191 /* ordinary character, so just copy it */
196 /* Note: to reach this point in the code, we must have evaded
197 * all "continue" statements. To do that, we must have hit
198 * a metacharacter that involves copying.
201 /* if there is nothing to copy, loop */
205 /* copy over a portion of the original */
214 /* convert to uppercase */
215 *dst
++ = toupper(*cpy
++);
220 /* convert to lowercase */
221 *dst
++ = tolower(*cpy
++);
225 /* copy without any conversion */
229 /* \u and \l end automatically after the first char */
230 if (mod
&& (mod
== 'u' || mod
== 'l'))
239 #endif /* NO_MAGIC */