我想要的是,我认为,相对简单:
> Bin = <<"Hello.world.howdy?">>.
> split(Bin, ".").
[<<"Hello">>, <<"world">>, <<"howdy?">>]
任何指针?
binary:split(Bin,<<".">>).
在 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版本。
上面的代码在 std 上更快。只有 BEAM 字节码,在 HiPE 中没有,两者几乎相同。
编辑:请注意此代码自 R14B 以来已被新模块二进制文件废弃。改为使用binary:split(Bin, <<".">>, [global]).
。
当前没有与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.
这是一种方法:
re:split(<<"Hello.world.howdy?">>, "\\.").