How To Pattern Match Bitstrings And Binaries In Elixir — Tentamen Software Testing Blog

String Pattern Matching


Bitstrings And Binaries

Using binary syntax and pattern-matching operator, we first pattern-match each byte of three-byte binary into separate variables in the above screenshot.

Then we forced one MatchError.

We can pattern-match just what is interesting for us.

It is also possible to pattern-match binary data in smaller chunks of bits. 156 in binary is "10011100". When we split it into two four-bit values, we split 156 into 9 and 12 because 9 => "1001" and 12 => "1100". Note that we used Integer.to_string it because Elixir Strings are binaries.

Let’s pattern match Croatian letters. Š Đ and Č. For them, we need 16 bytes because those are encoded using. Decimal UTF8 value for Š is 50592.

We could also do something like regular expressions with the help of operator. Here we store the testers name into name variable.

When To Use It


  • string pattern matching
  • pattern matching instead of regex

Originally published at on January 22, 2021.

Founder of Tentamen, software testing agency.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store