From e37a2e54ab7229b332c903ed380297b99963e429 Mon Sep 17 00:00:00 2001 From: nicm Date: Wed, 8 Jul 2026 11:04:51 +0000 Subject: [PATCH] Fix regsub with anchor at start of pattern, GitHub issue 5341. --- regsub.c | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/regsub.c b/regsub.c index 62d750d8a..9e33a88ab 100644 --- a/regsub.c +++ b/regsub.c @@ -90,6 +90,15 @@ regsub(const char *pattern, const char *with, const char *text, int flags) */ regsub_copy(&buf, &len, text, last, m[0].rm_so + start); + /* For anchored patterns, replace the first match only. */ + if (*pattern == '^') { + regsub_expand(&buf, &len, with, text + start, m, + nitems(m)); + last = start + m[0].rm_eo; + regsub_copy(&buf, &len, text, last, end); + break; + } + /* * If the last match was empty and this one isn't (it is either * later or has matched text), expand this match. If it is @@ -109,12 +118,6 @@ regsub(const char *pattern, const char *with, const char *text, int flags) start += m[0].rm_eo + 1; empty = 1; } - - /* Stop now if anchored to start. */ - if (*pattern == '^') { - regsub_copy(&buf, &len, text, start, end); - break; - } } buf[len] = '\0';