Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String.replace in Elixir

Tags:

elixir

I need to convert this string

"/{foo}/{bar}.{format}"

in

"/#{a["foo"]}/#{a["bar"]}.#{a["format"]}"

Because I have a list with these attributes. for instance

a["foo"] = "home"
a["bar"] = "picture"
a["format"] = "jpg"

I try to something like this

String.replace(a,"{",~s(#{))

But I got this error (

SyntaxError) iex:8: unexpected token: )

I try even a regexp to create a List to try to have my result but I don't understand how can I apply this regexp ([^{]*?)\w(?=\})

like image 428
monkeyUser Avatar asked May 16 '26 16:05

monkeyUser


2 Answers

Assuming you want the string "/home/picture.jpg" as the result, you can use Regex.replace/3 with a function as replacement:

map = %{
  "foo" => "home",
  "bar" => "picture",
  "format" => "jpg",
}

string = "/{foo}/{bar}.{format}"

Regex.replace(~r/{([a-z]+)?}/, string, fn _, match ->
  map[match]
end)
|> IO.inspect

Output:

"/home/picture.jpg"
like image 65
Dogbert Avatar answered May 22 '26 06:05

Dogbert


Use capital S in sigil:

iex> a = "/{foo}/{bar}.{format}"
iex> IO.puts String.replace(a,"{",~S(#{))
/#{foo}/#{bar}.#{format}

Sigils are explained here: https://elixir-lang.org/getting-started/sigils.html#interpolation-and-escaping-in-sigils

like image 37
denis.peplin Avatar answered May 22 '26 07:05

denis.peplin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!