jshadyjlo
jshadyjlo

Reputation: 133

Erlang binary pattern matching fails

Why does this issue a badmatch error? I can't figure out why this would fail:

<<IpAddr, ":*:*">> = <<"2a01:e34:ee8b:c080:a542:ffaf:*:*">>.

Upvotes: 2

Views: 1680

Answers (2)

rvirding
rvirding

Reputation: 20916

Pattern matching of a binary proceeds left-to-right so it will match IpAddr first before it tries the following segment. There is no back-tracking until there is a match. A default typed variable like IpAddr matches one byte. See Bit Syntax Expressions and Bit Syntax for a proper description and more examples.

As alternative to using pattern matching here you might consider using the binary module. There are two functions which could be useful to you: binary:match/2/3 and binary:split/2/3. These search which may better fit your problem.

As a last alternative you could try using regular expressions and the re module.

Upvotes: 5

juro
juro

Reputation: 641

You need to specify the size of IpAddr so that it can be pattern-matched:

1> <<IpAddr:28/binary, ":*:*">> = <<"2a01:e34:ee8b:c080:a542:ffaf:*:*">>.
<<"2a01:e34:ee8b:c080:a542:ffaf:*:*">>
2> IpAddr.
<<"2a01:e34:ee8b:c080:a542:ffaf">>

Upvotes: 6

Related Questions