Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get substring from a String in Elixir

Tags:

string

elixir

In Ruby, I can go:

"Sergio"[1..-1] #> "ergio"

Doing the same in Elixir gives a runtime error:

iex(1)> "Sergio"[1..-1]
** (CompileError) iex:1: the Access syntax and calls to Access.get/2 are not available for the value: "Sergio"

Also tried:

iex(1)> String.slice("Sergio", 1, -1)
** (FunctionClauseError) no function clause matching in String.slice/3
(elixir) lib/string.ex:1471: String.slice("Sergio", 1, -1)

How can I get a substring from a string in Elixir?

like image 405
Sergio Tapia Avatar asked Oct 25 '16 03:10

Sergio Tapia


2 Answers

You can use String.slice/2:

iex(1)> String.slice("Sergio", 1..-1)
"ergio"
iex(2)> String.slice("Sergio", 0..-3)                
"Serg"
like image 88
Sergio Tapia Avatar answered Nov 20 '22 08:11

Sergio Tapia


If you want to get substring without first letter you can use also:

"Sergio" |> String.to_charlist() |> tl() |> to_string()

And another way to get substring from the end is:

a = "Sergio"
len = String.length(a)
String.slice(a, -len + 1, len - 1) # "ergio"
#this -len + 1 is -1(len - 1) and it's exact to Ruby's -1 when slicing string.
like image 37
PatNowak Avatar answered Nov 20 '22 08:11

PatNowak