[erlang-questions] Validating binaries

zxq9 zxq9@REDACTED
Tue Aug 11 17:13:23 CEST 2015


On 2015年8月11日 火曜日 15:49:41 Roger Lipscombe wrote:
> On 11 August 2015 at 15:39, Roger Lipscombe <roger@REDACTED> wrote:
> > Simple question: what's the most efficient way to validate that a
> > binary value is of a certain length, and contains only certain
> > characters?
> >
> > I've got the following:
> 
> [snip]
> 
> It might be worth pointing out that I only have to deal with the
> following combinations: 16 lower-case hex characters or 24 upper-case
> hex characters. ASCII encoding. So would something like the following
> be better?
> 
> validate_lower_case_hex_16(<<C1:8, C2:8, ...)
>   when
>     (C1 >= $0, C1 =< $9; C1 >= $a, C1 =< $f),
>     (C2 >= $0, C2 =< $9; C2 >= $a, C2 =< $f),
>     ... % lots of repitition here
>   ->
>     Value;

Hrm...

Something along the lines of (the following totally untested code...):


validate_hex(Value = <<_:16/binary>>) -> validate_hex(Value, "([0-9a-f]*)");
validate_hex(Value = <<_:24/binary>>) -> validate_hex(Value, "([0-9A-F]*)");
validate_hex(_) -> erlang:error(validation_failed).

validate_hex(Value, Pattern) ->
    case re:run(Value, Pattern, [{capture, [1], binary}]) of
        {match, [Value]} -> Value;
        _                -> erlang:error(validation_failed)
    end.


No idea how something like that would perform.

-Craig



More information about the erlang-questions mailing list