How can you match the first n characters from a string? Something like:
def take(n) do
head :: size(n) <> rest = "my string"
end
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.
A bitstring is a fundamental data type in Elixir, denoted with the <<>> syntax.
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.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With