From 11aceb66c81d464593790a566c491cf3e649b814 Mon Sep 17 00:00:00 2001 From: Liam Miller-Cushon Date: Wed, 13 May 2026 20:50:26 +0200 Subject: [PATCH 1/2] Fix handling of `split` when the input is fully matched and the limit is 0 The specification for limit is > If `limit == 0`, empty strings that would occur at the end of the array are omitted https://github.com/google/re2j/issues/197 --- java/com/google/re2j/Pattern.java | 2 +- javatests/com/google/re2j/PatternTest.java | 6 ++++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/java/com/google/re2j/Pattern.java b/java/com/google/re2j/Pattern.java index dfe1bf18..b6831883 100644 --- a/java/com/google/re2j/Pattern.java +++ b/java/com/google/re2j/Pattern.java @@ -272,7 +272,7 @@ private String[] split(Matcher m, int limit) { result.add(m.substring(last, m.inputLength())); } - if (limit != 0 || result.isEmpty()) { + if (limit != 0 || (result.isEmpty() && !(last == m.inputLength() && last > 0))) { result.add(m.substring(last, m.inputLength())); } diff --git a/javatests/com/google/re2j/PatternTest.java b/javatests/com/google/re2j/PatternTest.java index 8a4f897f..62b87a4f 100644 --- a/javatests/com/google/re2j/PatternTest.java +++ b/javatests/com/google/re2j/PatternTest.java @@ -162,6 +162,12 @@ public void testSplit() { ApiTestUtils.testSplit("x*", "foo", 1, new String[] {"foo"}); ApiTestUtils.testSplit("x*", "f", 2, new String[] {"f", ""}); ApiTestUtils.testSplit(":", ":a::b", new String[] {"", "a", "", "b"}); + + // From https://github.com/google/re2j/issues/197. + // Test split when input is fully matched and limit is 0. + ApiTestUtils.testSplit("\\s+", " ", new String[] {}); + ApiTestUtils.testSplit("\\s+", " foo", new String[] {"", "foo"}); + ApiTestUtils.testSplit("\\s+", "foo ", new String[] {"foo"}); } @Test From e1205133a12ab40623af5c362ee2255e9047690d Mon Sep 17 00:00:00 2001 From: Liam Miller-Cushon Date: Fri, 15 May 2026 10:17:32 +0200 Subject: [PATCH 2/2] Add another test for splitting empty strings --- javatests/com/google/re2j/PatternTest.java | 1 + 1 file changed, 1 insertion(+) diff --git a/javatests/com/google/re2j/PatternTest.java b/javatests/com/google/re2j/PatternTest.java index 62b87a4f..c21b8d2d 100644 --- a/javatests/com/google/re2j/PatternTest.java +++ b/javatests/com/google/re2j/PatternTest.java @@ -168,6 +168,7 @@ public void testSplit() { ApiTestUtils.testSplit("\\s+", " ", new String[] {}); ApiTestUtils.testSplit("\\s+", " foo", new String[] {"", "foo"}); ApiTestUtils.testSplit("\\s+", "foo ", new String[] {"foo"}); + ApiTestUtils.testSplit("\\s+", "", new String[] {""}); } @Test