diff --git a/mysql-test/r/func_regexp_pcre.result b/mysql-test/r/func_regexp_pcre.result index b777af767cb..641c4fddbf7 100644 --- a/mysql-test/r/func_regexp_pcre.result +++ b/mysql-test/r/func_regexp_pcre.result @@ -839,3 +839,9 @@ SELECT REGEXP_REPLACE('abc','^(.*)(.*)$','\\1/\\2'); REGEXP_REPLACE('abc','^(.*)(.*)$','\\1/\\2') /abc SET default_regex_flags=DEFAULT; +# +# MDEV-6965 non-captured group \2 in regexp_replace +# +SELECT REGEXP_REPLACE('1 foo and bar', '(\\d+) foo and (\\d+ )?bar', '\\1 this and \\2that'); +REGEXP_REPLACE('1 foo and bar', '(\\d+) foo and (\\d+ )?bar', '\\1 this and \\2that') +1 this and that diff --git a/mysql-test/t/func_regexp_pcre.test b/mysql-test/t/func_regexp_pcre.test index 7e8df840239..6710f5cf096 100644 --- a/mysql-test/t/func_regexp_pcre.test +++ b/mysql-test/t/func_regexp_pcre.test @@ -397,3 +397,8 @@ SET default_regex_flags='UNGREEDY'; SELECT REGEXP_SUBSTR('abc','.+'); SELECT REGEXP_REPLACE('abc','^(.*)(.*)$','\\1/\\2'); SET default_regex_flags=DEFAULT; + +--echo # +--echo # MDEV-6965 non-captured group \2 in regexp_replace +--echo # +SELECT REGEXP_REPLACE('1 foo and bar', '(\\d+) foo and (\\d+ )?bar', '\\1 this and \\2that'); diff --git a/sql/item_strfunc.cc b/sql/item_strfunc.cc index f4629b6fc0f..339d053eade 100644 --- a/sql/item_strfunc.cc +++ b/sql/item_strfunc.cc @@ -1379,12 +1379,15 @@ bool Item_func_regexp_replace::append_replacement(String *str, break; /* End of line */ beg+= cnv; - if ((n= ((int) wc) - '0') >= 0 && n <= 9 && n < re.nsubpatterns()) + if ((n= ((int) wc) - '0') >= 0 && n <= 9) { - /* A valid sub-pattern reference found */ - int pbeg= re.subpattern_start(n), plength= re.subpattern_end(n) - pbeg; - if (str->append(source->str + pbeg, plength, cs)) - return true; + if (n < re.nsubpatterns()) + { + /* A valid sub-pattern reference found */ + int pbeg= re.subpattern_start(n), plength= re.subpattern_end(n) - pbeg; + if (str->append(source->str + pbeg, plength, cs)) + return true; + } } else {