+static void print_subst_w_backrefs(const char *line, const char *replace, regmatch_t *regmatch)
+{
+ int i;
+
+ /* go through the replacement string */
+ for (i = 0; replace[i]; i++) {
+ /* if we find a backreference (\1, \2, etc.) print the backref'ed * text */
+ if (replace[i] == '\\' && isdigit(replace[i+1])) {
+ int j;
+ char tmpstr[2];
+ int backref;
+ ++i; /* i now indexes the backref number, instead of the leading slash */
+ tmpstr[0] = replace[i];
+ tmpstr[1] = 0;
+ backref = atoi(tmpstr);
+ /* print out the text held in regmatch[backref] */
+ for (j = regmatch[backref].rm_so; j < regmatch[backref].rm_eo; j++)
+ fputc(line[j], stdout);
+ }
+
+ /* if we find a backslash escaped character, print the character */
+ else if (replace[i] == '\\') {
+ ++i;
+ fputc(replace[i], stdout);
+ }
+
+ /* if we find an unescaped '&' print out the whole matched text.
+ * fortunately, regmatch[0] contains the indicies to the whole matched
+ * expression (kinda seems like it was designed for just such a
+ * purpose...) */
+ else if (replace[i] == '&' && replace[i-1] != '\\') {
+ int j;
+ for (j = regmatch[0].rm_so; j < regmatch[0].rm_eo; j++)
+ fputc(line[j], stdout);
+ }
+ /* nothing special, just print this char of the replacement string to stdout */
+ else
+ fputc(replace[i], stdout);
+ }
+}
+