2

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

2 Answers 2

9

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"
Sign up to request clarification or add additional context in comments.

Comments

6

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

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.