アーランでバイナリを分割するにはどうすればよいですか

StackOverflow https://stackoverflow.com/questions/428124

  •  06-07-2019
  •  | 
  •  

質問

私が欲しいのは、比較的シンプルだと思います:

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

任意のポインター?

役に立ちましたか?

解決

バイナリ文字列で機能するlists:split/2に相当する現在のOTP関数はありません。 EEP-9 が公開されるまで、次のようなバイナリ分割関数を作成できます。 :

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.

他のヒント

binary:split(Bin,<<".">>).

バイナリ .erlang.org / eeps / eep-0031.html "rel =" noreferrer "> EEP31 (および EEP9 )が Erts-5.8に追加されました(OTP-8217を参照):

1> Bin = <<"Hello.world.howdy?">>.
<<"Hello.world.howdy?">>
2> binary:split(Bin, <<".">>, [global]).
[<<"Hello">>,<<"world">>,<<"howdy?">>]

R12Bで動作するバイナリ分割のバージョンは約15%高速です:

split2(Bin, Chars) ->
    split2(Chars, Bin, 0, []).

split2(Chars, Bin, Idx, Acc) ->
    case Bin of
        <<This:Idx/binary, Char, Tail/binary>> ->
            case lists:member(Char, Chars) of
                false ->
                    split2(Chars, Bin, Idx+1, Acc);
                true ->
                    split2(Chars, Tail, 0, [This|Acc])
            end;
        <<This:Idx/binary>> ->
            lists:reverse(Acc, [This])
    end.

R11B以前を使用している場合は、archaelus バージョン<代わりに/ a>。

上記のコードはstdで高速です。ビームバイトコードのみ。HiPEではなく、両方ともほぼ同じです。

編集:新しいモジュールバイナリによって廃止されたこのコードに注意してください R14B以降。代わりにbinary:split(Bin, <<".">>, [global]).を使用してください。

1つの方法を次に示します。

re:split(<<"Hello.world.howdy?">>, "\\.").
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top