This is an automated email from the ASF dual-hosted git repository.
mrhhsg pushed a commit to branch branch-4.2
in repository https://gitbox.apache.org/repos/asf/doris.git
The following commit(s) were added to refs/heads/branch-4.2 by this push:
new fa8a3b208fd branch-4.2: [fix](be) Preserve regexp anchors across
repeated searches #68428 (#71285)
fa8a3b208fd is described below
commit fa8a3b208fd026ed1c7777fd6259b44a1f4f35c7
Author: Jerry Hu <[email protected]>
AuthorDate: Fri Dec 4 10:31:05 2026 +0800
branch-4.2: [fix](be) Preserve regexp anchors across repeated searches
#68428 (#71285)
### What problem does this PR solve?
Issue Number: None
Related PR: #68428
Cherry-picked from #68428 (master) to `branch-4.2`.
Repeated RE2 searches previously treated each remaining suffix as a new
input. This could make `^` match repeatedly and lose the original
word-boundary context in `regexp_extract_all`, `regexp_count`, and
`split_by_regexp`. Empty matches also advanced from the previous search
position by one byte instead of from the actual match position.
This backport:
- Keeps the original RE2 subject and advances only the search offset.
- Advances empty extraction/counting matches by one UTF-8 character from
their actual position, falls back to one-byte progress for malformed
UTF-8, and stops at an empty end-of-input match. Empty matches remain
excluded from extraction results and counts.
- Keeps split-match offsets relative to the original input and removes
suffix copying/searching from repeated extraction.
- Preserves the target branch's existing Boost.Regex behavior,
empty-match filtering, and split limits.
Branch-specific adaptations: retain the existing Boost zero-width
coverage and compile-check guards. `branch-4.2` does not provide
`regexp_extract_all_array`, so this backport does not introduce that
separate API; SQL coverage uses the existing functions and its expected
output was regenerated and verified by a normal comparison run.
### Release note
Fix incorrect anchors and word-boundary context during repeated regexp
searches, and correct UTF-8 progress after empty extraction/counting
matches.
### Check List (For Author)
- Test
- [x] Unit Test: **18/18 passed under ASAN**.
```bash
./run-be-ut.sh --run -j 48
--filter='FunctionLikeTest.regexp*:FunctionLikeTest.split_by_regexp_preserves_original_anchor:function_string_test.function_regexp_count_mixed_const_test'
```
- [x] Regression test: **5/5 suites passed**, with no failed, fatal, or
skipped scripts, after loading the existing shared SQL fixtures. The new
suite was also generated and rerun in normal comparison mode. The
regression wrapper invokes this runner with an isolated configuration:
```bash
./run-regression-test.sh --conf <isolated-regression-conf> --run \
-d query_p0/sql_functions/string_functions \
-s
test_regexp_repeated_search_anchor,test_string_function_regexp,test_split_by_regexp,test_regexp_extended_nonconstant_pattern,test_regexp_chinese
```
- [x] Manual test:
- RELEASE BE and FE production build:
```bash
env FE_MAVEN_THREADS=16 MVN_OPT=-Dmaven.test.skip=true ./build.sh --be
--fe -j 48
```
- FE Checkstyle: zero violations.
- clang-format 16: all four changed C++ files passed.
- `git diff --check`: passed.
Validation scope: FE unit tests were not run. Production packaging used
`-Dmaven.test.skip=true` because the unchanged
`GroupCommitManagerBackendSelectionTest` fails test compilation with an
unresolved `Assertions` symbol; Checkstyle remained enabled. SQL
regression used native BE functions with Java support disabled; Java UDF
and Java-based external-catalog paths were not tested. Standalone
clang-tidy was not run.
- Behavior changed:
- [ ] No.
- [x] Yes. Repeated RE2 searches preserve the original input's anchors
and boundaries; empty-match progress respects UTF-8 character
boundaries.
- Does this need documentation?
- [x] No. Backport of a correctness fix; no new API or configuration.
- [ ] Yes.
### Check List (For Reviewer who merge this PR)
- [ ] Confirm the release note
- [ ] Confirm test cases
- [ ] Confirm document
- [ ] Add branch pick label
---
be/src/exprs/function/function_regexp.cpp | 48 ++++++++++++++--------
be/src/exprs/function/function_split_by_regexp.cpp | 18 ++++----
be/test/exprs/function/function_like_test.cpp | 38 +++++++++++++++++
be/test/exprs/function/function_string_test.cpp | 4 ++
.../test_regexp_repeated_search_anchor.out | 9 ++++
.../test_regexp_repeated_search_anchor.groovy | 35 ++++++++++++++++
6 files changed, 128 insertions(+), 24 deletions(-)
diff --git a/be/src/exprs/function/function_regexp.cpp
b/be/src/exprs/function/function_regexp.cpp
index 7fba735dfb7..48a2ce31f9b 100644
--- a/be/src/exprs/function/function_regexp.cpp
+++ b/be/src/exprs/function/function_regexp.cpp
@@ -19,6 +19,7 @@
#include <re2/re2.h>
#include <re2/stringpiece.h>
#include <stddef.h>
+#include <unicode/utf8.h>
#include <boost/regex.hpp>
#include <memory>
@@ -56,6 +57,24 @@
namespace doris {
#include "common/compile_check_begin.h"
+static bool advance_re2_search_position(const char* data, size_t size,
+ const re2::StringPiece& match, size_t&
pos) {
+ const size_t match_pos = match.data() - data;
+ if (match.empty()) {
+ if (match_pos == size) {
+ return false;
+ }
+ size_t next_pos = match_pos;
+ UChar32 character;
+ U8_NEXT(data, next_pos, size, character);
+ // Doris strings can contain malformed UTF-8, so make byte-wise
progress on decode failure.
+ pos = character < 0 ? match_pos + 1 : next_pos;
+ } else {
+ pos = match_pos + match.size();
+ }
+ return true;
+}
+
// Helper structure to hold either RE2 or Boost.Regex
struct RegexpExtractEngine {
std::unique_ptr<re2::RE2> re2_regex;
@@ -146,28 +165,26 @@ struct RegexpExtractEngine {
return; // No capturing groups
}
+ const re2::StringPiece input(data, size);
size_t pos = 0;
while (pos < size) {
- const char* str_pos = data + pos;
- size_t str_size = size - pos;
std::vector<re2::StringPiece> matches(max_matches);
- bool success = re2_regex->Match(re2::StringPiece(str_pos,
str_size), 0, str_size,
- re2::RE2::UNANCHORED,
matches.data(), max_matches);
+ bool success = re2_regex->Match(input, pos, size,
re2::RE2::UNANCHORED,
+ matches.data(), max_matches);
if (!success) {
break;
}
+ const bool can_continue = advance_re2_search_position(data,
size, matches[0], pos);
if (matches[0].empty()) {
- pos += 1;
+ if (!can_continue) {
+ break;
+ }
continue;
}
// Extract first capturing group
if (matches.size() > 1 && !matches[1].empty()) {
results.emplace_back(matches[1].data(), matches[1].size());
}
- // Move position forward
- auto offset = std::string(str_pos, str_size)
- .find(std::string(matches[0].data(),
matches[0].size()));
- pos += offset + matches[0].size();
}
} else if (is_boost()) {
// Iterate over the whole input instead of re-running regex_search
on a
@@ -220,23 +237,22 @@ struct RegexpCountImpl {
const auto str = str_col.value_at(index_now);
int count = 0;
size_t pos = 0;
+ const re2::StringPiece input(str.data, str.size);
while (pos < str.size) {
- auto str_pos = str.data + pos;
- auto str_size = str.size - pos;
- re2::StringPiece str_sp_current = re2::StringPiece(str_pos,
str_size);
re2::StringPiece match;
- bool success = re->Match(str_sp_current, 0, str_size,
re2::RE2::UNANCHORED, &match, 1);
+ bool success = re->Match(input, pos, str.size,
re2::RE2::UNANCHORED, &match, 1);
if (!success) {
break;
}
+ const bool can_continue = advance_re2_search_position(str.data,
str.size, match, pos);
if (match.empty()) {
- pos += 1;
+ if (!can_continue) {
+ break;
+ }
continue;
}
count++;
- size_t match_start = match.data() - str_sp_current.data();
- pos += match_start + match.size();
}
return count;
diff --git a/be/src/exprs/function/function_split_by_regexp.cpp
b/be/src/exprs/function/function_split_by_regexp.cpp
index 3cf78de7d03..1b694b4b0d5 100644
--- a/be/src/exprs/function/function_split_by_regexp.cpp
+++ b/be/src/exprs/function/function_split_by_regexp.cpp
@@ -44,6 +44,7 @@ public:
bool get(const char*& token_begin, const char*& token_end);
private:
+ const char* _begin;
const char* _pos;
const char* _end;
@@ -53,12 +54,12 @@ private:
re2::RE2* _re2 = nullptr;
unsigned _number_of_subpatterns = 0;
- unsigned match(const char* subject, size_t subject_size,
std::vector<Match>& matches,
- unsigned limit) const;
+ unsigned match(const char* subject, size_t subject_size, size_t start_pos,
+ std::vector<Match>& matches, unsigned limit) const;
};
-unsigned RegexpSplit::match(const char* subject, size_t subject_size,
std::vector<Match>& matches,
- unsigned limit) const {
+unsigned RegexpSplit::match(const char* subject, size_t subject_size, size_t
start_pos,
+ std::vector<Match>& matches, unsigned limit) const
{
matches.clear();
if (limit == 0) {
@@ -68,8 +69,8 @@ unsigned RegexpSplit::match(const char* subject, size_t
subject_size, std::vecto
limit = std::min(limit, _number_of_subpatterns + 1);
std::vector<re2::StringPiece> pieces(limit);
- if (!_re2->Match({subject, subject_size}, 0, subject_size,
re2::RE2::UNANCHORED, pieces.data(),
- limit)) {
+ if (!_re2->Match({subject, subject_size}, start_pos, subject_size,
re2::RE2::UNANCHORED,
+ pieces.data(), limit)) {
return 0;
} else {
matches.resize(limit);
@@ -96,6 +97,7 @@ void RegexpSplit::init(re2::RE2* re2, int32_t max_splits) {
// Called for each next string.
void RegexpSplit::set(const char* pos, const char* end) {
+ _begin = pos;
_pos = pos;
_end = end;
_splits = 0;
@@ -135,12 +137,12 @@ bool RegexpSplit::get(const char*& token_begin, const
char*& token_end) {
}
}
- if (!match(_pos, _end - _pos, _matches, _number_of_subpatterns + 1) ||
+ if (!match(_begin, _end - _begin, _pos - _begin, _matches,
_number_of_subpatterns + 1) ||
!_matches[0].length) {
token_end = _end;
_pos = _end + 1;
} else {
- token_end = _pos + _matches[0].offset;
+ token_end = _begin + _matches[0].offset;
_pos = token_end + _matches[0].length;
++_splits;
}
diff --git a/be/test/exprs/function/function_like_test.cpp
b/be/test/exprs/function/function_like_test.cpp
index e4f6d067c6a..176c9bad2c5 100644
--- a/be/test/exprs/function/function_like_test.cpp
+++ b/be/test/exprs/function/function_like_test.cpp
@@ -27,6 +27,7 @@
#include "core/column/column_const.h"
#include "core/column/column_string.h"
#include "core/column/column_vector.h"
+#include "core/data_type/data_type_array.h"
#include "core/data_type/data_type_nullable.h"
#include "core/data_type/data_type_number.h"
#include "core/data_type/data_type_string.h"
@@ -556,12 +557,18 @@ TEST(FunctionLikeTest, regexp_extract_or_null) {
TEST(FunctionLikeTest, regexp_extract_all) {
std::string func_name = "regexp_extract_all";
+ const std::string word_boundary_input(10000, 'a');
+ const std::string invalid_utf8_input {static_cast<char>(0xC3), 'A'};
DataSet data_set = {
{{std::string("x=a3&x=18abc&x=2&y=3&x=4&x=17bcd"),
std::string("x=([0-9]+)([a-z]+)")},
std::string("['18','17']")},
{{std::string("x=a3&x=18abc&x=2&y=3&x=4"),
std::string("^x=([a-z]+)([0-9]+)")},
std::string("['a']")},
+ {{std::string("aaa"), std::string("(^a)")}, std::string("['a']")},
+ {{word_boundary_input, std::string("(\\b)")}, std::string("")},
+ {{std::string("é"), std::string("(?:^)|(\\C)")}, std::string("")},
+ {{invalid_utf8_input, std::string("(?:^)|(\\C)")},
std::string("['A']")},
{{std::string("http://a.m.baidu.com/i41915173660.htm"),
std::string("i([0-9]+)")},
std::string("['41915173660']")},
{{std::string("http://a.m.baidu.com/i41915i73660.htm"),
std::string("i([0-9]+)")},
@@ -648,6 +655,37 @@ TEST(FunctionLikeTest,
regexp_extract_all_boost_zero_width_match) {
run_case("xxa?b", "(?<=a)|^(b)", "");
}
+TEST(FunctionLikeTest, split_by_regexp_preserves_original_anchor) {
+ const std::string input = "aaa";
+ const std::string pattern = "^a";
+ auto string_type = std::make_shared<DataTypeString>();
+ auto return_type =
+
std::make_shared<DataTypeArray>(make_nullable(std::make_shared<DataTypeString>()));
+
+ auto input_column = ColumnString::create();
+ input_column->insert_data(input.data(), input.size());
+ auto pattern_column = ColumnString::create();
+ pattern_column->insert_data(pattern.data(), pattern.size());
+
+ Block block;
+ block.insert({std::move(input_column), string_type, "str"});
+ block.insert({ColumnConst::create(std::move(pattern_column), 1),
string_type, "pattern"});
+ block.insert({nullptr, return_type, "result"});
+
+ ColumnsWithTypeAndName arg_cols = {block.get_by_position(0),
block.get_by_position(1)};
+ auto function =
SimpleFunctionFactory::instance().get_function("split_by_regexp", arg_cols,
+
return_type);
+ ASSERT_TRUE(function != nullptr);
+
+ FunctionUtils fn_utils({}, {string_type, string_type}, false);
+ auto* context = fn_utils.get_fn_ctx();
+ ASSERT_EQ(Status::OK(), function->execute(context, block, {0, 1}, 2, 1));
+
+ const auto& result_column = block.get_by_position(2).column;
+ ASSERT_TRUE(result_column.get() != nullptr);
+ EXPECT_EQ(R"(["", "aa"])", return_type->to_string(*result_column, 0));
+}
+
TEST(FunctionLikeTest, regexp_replace) {
std::string func_name = "regexp_replace";
diff --git a/be/test/exprs/function/function_string_test.cpp
b/be/test/exprs/function/function_string_test.cpp
index 0152f704cd5..788a1b4c869 100644
--- a/be/test/exprs/function/function_string_test.cpp
+++ b/be/test/exprs/function/function_string_test.cpp
@@ -4192,6 +4192,10 @@ TEST(function_string_test,
function_regexp_count_mixed_const_test) {
{{std::string("a1b2346c3d"), std::string("\\d+")},
std::int32_t(3)},
{{std::string("abcd"), std::string("")}, std::int32_t(0)},
{{std::string("book keeper"), std::string("oo|ee")},
std::int32_t(2)},
+ {{std::string("aaa"), std::string("^a")}, std::int32_t(1)},
+ {{std::string(10000, 'a'), std::string("\\b")}, std::int32_t(0)},
+ {{std::string("é"), std::string("^|\\C")}, std::int32_t(0)},
+ {{std::string {static_cast<char>(0xC3), 'A'},
std::string("^|\\C")}, std::int32_t(1)},
{{Null(), std::string("\\d+")}, Null()},
{{std::string("abcd"), Null()}, Null()},
};
diff --git
a/regression-test/data/query_p0/sql_functions/string_functions/test_regexp_repeated_search_anchor.out
b/regression-test/data/query_p0/sql_functions/string_functions/test_regexp_repeated_search_anchor.out
new file mode 100644
index 00000000000..d95290ea6f2
--- /dev/null
+++
b/regression-test/data/query_p0/sql_functions/string_functions/test_regexp_repeated_search_anchor.out
@@ -0,0 +1,9 @@
+-- This file is automatically generated. You should know what you did if you
want to edit this
+-- !anchor_functions --
+1 ['a'] ["", "aa"] 2
+
+-- !word_boundary_functions --
+ 0
+
+-- !multibyte_empty_match_functions --
+ 0
diff --git
a/regression-test/suites/query_p0/sql_functions/string_functions/test_regexp_repeated_search_anchor.groovy
b/regression-test/suites/query_p0/sql_functions/string_functions/test_regexp_repeated_search_anchor.groovy
new file mode 100644
index 00000000000..38f94c09d7e
--- /dev/null
+++
b/regression-test/suites/query_p0/sql_functions/string_functions/test_regexp_repeated_search_anchor.groovy
@@ -0,0 +1,35 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+suite("test_regexp_repeated_search_anchor") {
+ qt_anchor_functions """
+ SELECT regexp_count('aaa', '^a'),
+ regexp_extract_all('aaa', '(^a)'),
+ split_by_regexp('aaa', '^a'),
+ size(split_by_regexp('aaa', '^a'))
+ """
+
+ qt_word_boundary_functions """
+ SELECT regexp_extract_all(repeat('a', 10000), '(\\\\b)'),
+ regexp_count(repeat('a', 10000), '\\\\b')
+ """
+
+ qt_multibyte_empty_match_functions """
+ SELECT regexp_extract_all('é', '(?:^)|(\\\\C)'),
+ regexp_count('é', '^|\\\\C')
+ """
+}
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]