Skip to content

Regex.split with trailing \K works incorrectly #14467

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
error256 opened this issue May 3, 2025 · 3 comments · Fixed by #14468
Closed

Regex.split with trailing \K works incorrectly #14467

error256 opened this issue May 3, 2025 · 3 comments · Fixed by #14468

Comments

@error256
Copy link

error256 commented May 3, 2025

Elixir 1.18.3, Erlang/OTP 27.3.3

IO.inspect Regex.split ~r/b\K/, "ababab"
IO.inspect :re.split "ababab", "b\\K"

returns

["ab", "ab", "", "ab", "", ""]
["ab", "ab", "ab", ""]

I think Regex.split should return the same result as :re.split. Non-trailing \Ks and lookbehinds seem to work correctly, this is the only case.

@metemaad
Copy link

metemaad commented May 3, 2025 via email

@josevalim
Copy link
Member

Here is the relevant Erlang code that deals with this and we are missing, in particular the first branch of the case:

do_split(Subj, Offset, [[{MainI,MainL}|Sub]|T], NumSub, Limit, Group) ->
    NewOffset = MainI+MainL,
    KeptLen =  MainI - Offset,
    case {KeptLen,empty_sub(Sub),MainL} of
	{0,true,0} ->
	    do_split(Subj,NewOffset,T,NumSub,Limit,Group);
	_ ->
	    <<_:Offset/binary,Keep:KeptLen/binary,_/binary>> = Subj,
	    ESub = extend_subpatterns(Sub,NumSub),
	    Tail = do_split(Subj, NewOffset, T, NumSub, Limit - 1,Group),
	    case Group of
		false ->
		    [Keep | dig_subpatterns(Subj,lists:reverse(ESub),Tail)];
		true ->
		    [[Keep | dig_subpatterns(Subj,lists:reverse(ESub),[])]|
		     Tail]
	    end
    end.
empty_sub([]) ->
    true;
empty_sub([{_,0}|T]) ->
    empty_sub(T);
empty_sub(_) ->
    false.

@sabiwara
Copy link
Contributor

sabiwara commented May 4, 2025

@josevalim I came to the same conclusion and tried a fix, but it breaks some tests so it might be a breaking change?

iex> :re.split "abc", ""
["a", "b", "c", ""]

# main
iex> Regex.split ~r//, "abc"
["", "a", "b", "c", ""]

# the fix
iex> Regex.split ~r//, "abc"
["a", "b", "c", ""]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Development

Successfully merging a pull request may close this issue.

4 participants