Bitstring pattern matching end of string

Background

We have a simple string of variable size and we want the final 4 characters of the string. Our goal is to achieve this via pattern matching. No special reason, just trying to learn.

Code

This is what we have tried thus far:

<< _, ext :: bytes-4 >> = "my_file_name.exs"
<< _, ".", ext :: bytes-3 >> = "my_file_name.exs"

Trying both lines of code in IEx fails.

Questions

  1. Is it possible to pattern match a bitstring at the end of the string? (we know it works at the start)
  2. Are we doing something wrong? If so, what?

Only way to do it with pattern matching is reversing, which in itself might not be trivial. For your usecase there’s Path.extname though.

3 Likes

No, not exactly. If you know how many last characters you want to match you can hack it though:

str = "my_file_name.exs"
len = byte_size(str)
<<_::binary-size(len - 4), ?., ext::binary>> = str

But if you want extension, which is can be more than 3 characters (we aren’t using DOS anymore), then Path.extname/1 is the way to go.

5 Likes