+ sed_cmd->delimiter = olddelimiter;
+ return idx;
+}
+
+static int parse_subst_cmd(struct sed_cmd *sed_cmd, const char *substr)
+{
+ int oldidx, cflags = REG_NEWLINE;
+ char *match;
+ int idx = 0;
+ int j;
+
+ /*
+ * the string that gets passed to this function should look like this:
+ * s/match/replace/gIp
+ * || | |||
+ * mandatory optional
+ *
+ * (all three of the '/' slashes are mandatory)
+ */
+
+ /* verify that the 's' is followed by something. That something
+ * (typically a 'slash') is now our regexp delimiter... */
+ if (!substr[++idx])
+ error_msg_and_die("bad format in substitution expression");
+ else
+ sed_cmd->delimiter=substr[idx];
+
+ /* save the match string */
+ oldidx = idx+1;
+ idx = index_of_next_unescaped_regexp_delim(sed_cmd, substr, ++idx);
+ if (idx == -1)
+ error_msg_and_die("bad format in substitution expression");
+ match = xstrndup(substr + oldidx, idx - oldidx);
+
+ /* determine the number of back references in the match string */
+ /* Note: we compute this here rather than in the do_subst_command()
+ * function to save processor time, at the expense of a little more memory
+ * (4 bits) per sed_cmd */
+
+ /* sed_cmd->num_backrefs = 0; */ /* XXX: not needed? --apparently not */
+ for (j = 0; match[j]; j++) {
+ /* GNU/POSIX sed does not save more than nine backrefs */
+ if (match[j] == '\\' && match[j+1] == '(' && sed_cmd->num_backrefs <= 9)
+ sed_cmd->num_backrefs++;
+ }
+
+ /* save the replacement string */
+ oldidx = idx+1;
+ idx = index_of_next_unescaped_regexp_delim(sed_cmd, substr, ++idx);
+ if (idx == -1)
+ error_msg_and_die("bad format in substitution expression");
+ sed_cmd->replace = xstrndup(substr + oldidx, idx - oldidx);
+
+ /* process the flags */
+ while (substr[++idx]) {
+ switch (substr[idx]) {
+ case 'g':
+ sed_cmd->sub_g = 1;
+ break;
+ case 'I':
+ cflags |= REG_ICASE;
+ break;
+ case 'p':
+ sed_cmd->sub_p = 1;
+ break;
+ default:
+ /* any whitespace or semicolon trailing after a s/// is ok */
+ if (strchr("; \t\v\n\r", substr[idx]))
+ goto out;
+ /* else */
+ error_msg_and_die("bad option in substitution expression");
+ }
+ }
+
+out:
+ /* compile the match string into a regex */
+ sed_cmd->sub_match = (regex_t *)xmalloc(sizeof(regex_t));
+ xregcomp(sed_cmd->sub_match, match, cflags);
+ free(match);
+