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(?=\})
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"
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
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