How can i split a binary in erlang

后端 未结 5 1720
挽巷
挽巷 2020-12-31 14:57

What I want is, I think, relatively simple:

> Bin = <<\"Hello.world.howdy?\">>.
> split(Bin, \".\").
[<<\"Hello\">>, <<\"         


        
5条回答
  •  北海茫月
    2020-12-31 15:08

    There is no current OTP function that is the equivalent of lists:split/2 that works on a binary string. Until EEP-9 is made public, you might write a binary split function like:

    split(Binary, Chars) ->
        split(Binary, Chars, 0, 0, []).
    
    split(Bin, Chars, Idx, LastSplit, Acc)
      when is_integer(Idx), is_integer(LastSplit) ->
        Len = (Idx - LastSplit),
        case Bin of
            <<_:LastSplit/binary,
             This:Len/binary,
             Char,
             _/binary>> ->
                case lists:member(Char, Chars) of
                    false ->
                        split(Bin, Chars, Idx+1, LastSplit, Acc);
                    true ->
                        split(Bin, Chars, Idx+1, Idx+1, [This | Acc])
                end;
            <<_:LastSplit/binary,
             This:Len/binary>> ->
                lists:reverse([This | Acc]);
            _ ->
                lists:reverse(Acc)
        end.
    

提交回复
热议问题