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

How can you match the first n characters from a string? Sort of:

def take(n) do
  head :: size(n) <> rest = "my string"
end
+4
source share
1 answer

You can get the first bytes nusing 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 nUTF-8 code points using a single pattern, since UTF-8 characters can occupy a variable number of bytes, and pattern matching does not support Elixir. You can get the first (or a fixed number) of UTF-8 code points using ::utf8in the template:

iex(1)> <<cp::utf8>> <> rest = "ƒoo"
"ƒoo"
iex(2)> cp
402
iex(3)> <<cp::utf8>>
"ƒ"
iex(4)> rest
"oo"
+7
source

Source: https://habr.com/ru/post/1662011/


All Articles