24

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?

3 Answers 3

37

You can use String.slice/2:

iex(1)> String.slice("Sergio", 1..-1)
"ergio"
iex(2)> String.slice("Sergio", 0..-3)                
"Serg"
Sign up to request clarification or add additional context in comments.

3 Comments

Realize it's long after the fact but shouldn't that second expression be: String.slice("Sergio",0..3) (you've got -3 there).
@OnorioCatenacci In this case -3 and 3 return the same thing. -3 counts from the back, 3 from the front.
Elixir 1.12 update - negative steps are no longer supported you need to use a step operator: String.slice("Sergio", 1..-1//1) hexdocs.pm/elixir/1.12/Range.html
5

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.

1 Comment

Your first method returns a charlist not a string. You'd want to add |> to_string() to the end.
0

Besides String#slice there are also other ways to come up with the same result:

"Sergio" |> String.split(~r|(?<=\A.)|) |> List.last |> IO.inspect
#=> "ergio"
~r|(?<=\A.).*| |> Regex.run("Sergio") |> List.last |> IO.inspect
#=> "ergio"

In this particular case they bring no added value, but in some more complicated cases (as a reference to ruby's "Sergio"[/.../] they might have some sense.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.