# Bitstring pattern matching end of string

**URL:** <https://forum.elixirforum.com/t/bitstring-pattern-matching-end-of-string/25791>\
**Category:** Questions\
**Tags:** bitstring\
**Created:** [October 2, 2019, 9:52am UTC](https://forum.elixirforum.com/t/bitstring-pattern-matching-end-of-string/25791 "2019-10-02T09:52:10Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Fl4m3Ph03n1x](https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/fl4m3ph03n1x/32/11709_2.png) [@Fl4m3Ph03n1x](https://forum.elixirforum.com/u/Fl4m3Ph03n1x)\
**Post date:** [October 2, 2019, 9:52am UTC](https://forum.elixirforum.com/t/bitstring-pattern-matching-end-of-string/25791/1 "2019-10-02T09:52:10Z")

</div>

## 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:

```elixir
<< _, 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?

---

<div class="post-metadata">

**Author:** ![LostKobrakai](https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/lostkobrakai/32/3072_2.png) [@LostKobrakai](https://forum.elixirforum.com/u/LostKobrakai)\
**Post date:** [October 2, 2019, 9:59am UTC](https://forum.elixirforum.com/t/bitstring-pattern-matching-end-of-string/25791/2 "2019-10-02T09:59:13Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![hauleth](https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/hauleth/32/18942_2.png) [@hauleth](https://forum.elixirforum.com/u/hauleth)\
**Post date:** [October 2, 2019, 10:25am UTC](https://forum.elixirforum.com/t/bitstring-pattern-matching-end-of-string/25791/3 "2019-10-02T10:25:12Z")

</div>

> [@Fl4m3Ph03n1x](#):
>
> Is it possible to pattern match a bitstring at the end of the string?

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

```elixir
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.
