Skip to content

Commit 0e725fb

Browse files
bruceJosé Valim
authored andcommitted
Support String.split with an empty binary as the pattern.
As discussed in #1688, currently the following fails: iex> String.split "abc", "" ** (ArgumentError) argument error binary.erl:242: :binary.split/3 These changes add support for an empty binary pattern, piggybacking on the empty regular expression split (vs using `String.graphemes`, notably) so that the function continues to support the `:global` option. Users should probably be using `String.graphemes` for splitting, but this keeps the API consistent while fixing this exception. Closes #1688. Conflicts: lib/elixir/lib/string.ex
1 parent 4b317a7 commit 0e725fb

File tree

2 files changed

+14
-0
lines changed

2 files changed

+14
-0
lines changed

lib/elixir/lib/string.ex

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -184,20 +184,30 @@ defmodule String do
184184
["a", "b,c"]
185185
iex> String.split("a,b", %r{\\.})
186186
["a,b"]
187+
187188
iex> String.split("abc", %r{c})
188189
["ab", ""]
189190
iex> String.split("abc", %r{})
190191
["a", "b", "c", ""]
191192
iex> String.split("abc", %r{}, trim: true)
192193
["a", "b", "c"]
193194
195+
iex> String.split("abc", "")
196+
["a", "b", "c", ""]
197+
iex> String.split("abc", "", trim: true)
198+
["a", "b", "c"]
199+
iex> String.split("abc", "", global: false)
200+
["a", "bc"]
201+
194202
"""
195203
@spec split(t, t | [t] | Regex.t) :: [t]
196204
@spec split(t, t | [t] | Regex.t, Keyword.t) :: [t]
197205
def split(binary, pattern, options // [])
198206

199207
def split("", _pattern, _options), do: [""]
200208

209+
def split(binary, "", options), do: split(binary, %r"", options)
210+
201211
def split(binary, pattern, options) when is_regex(pattern) do
202212
Regex.split(pattern, binary, options)
203213
end

lib/elixir/test/elixir/string_test.exs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,10 @@ defmodule StringTest do
3636

3737
assert String.split(" a b c ", " ", trim: true) == ["a", "b", "c"]
3838
assert String.split(" a b c ", " ", trim: true, global: false) == ["a b c "]
39+
40+
assert String.split("abc", "") == ["a", "b", "c", ""]
41+
assert String.split("abc", "", global: false) == ["a", "bc"]
42+
assert String.split("abc", "", trim: true) == ["a", "b", "c"]
3943
end
4044

4145
test :split_with_regex do

0 commit comments

Comments
 (0)