Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to match the first n characters in an elixir string

Tags:

elixir

How can you match the first n characters from a string? Something like:

def take(n) do
  head :: size(n) <> rest = "my string"
end
like image 599
Peter Saxton Avatar asked Nov 26 '16 10:11

Peter Saxton


People also ask

What is pattern matching in Elixir?

Pattern matching allows developers to easily destructure data types such as tuples and lists. As we will see in the following chapters, it is one of the foundations of recursion in Elixir and applies to other types as well, like maps and binaries.

Is bitstring Elixir?

A bitstring is a fundamental data type in Elixir, denoted with the <<>> syntax.

What is Charlist?

A group of one or more characters enclosed by [ ] as part of Like operator's right string expression. This list contains single characters and/or character ranges which describe the characters in the list. A range of characters is indicated with a hyphen (-) between two characters.


1 Answers

You can get the first n bytes using pattern matching:

iex(1)> n = 4
4
iex(2)> <<head :: binary-size(n)>> <> rest = "my string"
"my string"
iex(3)> head
"my s"
iex(4)> rest
"tring"

You cannot get the first n UTF-8 codepoints using a single pattern since UTF-8 characters can occupy a variable number of bytes and pattern matching in Elixir does not support that. You can get the first (or a fixed number of) UTF-8 codepoints using ::utf8 in the pattern:

iex(1)> <<cp::utf8>> <> rest = "ƒoo"
"ƒoo"
iex(2)> cp
402
iex(3)> <<cp::utf8>>
"ƒ"
iex(4)> rest
"oo"
like image 87
Dogbert Avatar answered Jan 26 '23 22:01

Dogbert