Elixir String.replace在长生不老药中

Elixir String.replace在长生不老药中,elixir,Elixir,我需要转换这个字符串 "/{foo}/{bar}.{format}" 在 因为我有一个包含这些属性的列表。 比如说 a["foo"] = "home" a["bar"] = "picture" a["format"] = "jpg" 我试着做这样的事情 String.replace(a,"{",~s(#{)) 但我犯了这个错误( SyntaxError)iex:8:意外标记:) 我甚至尝试用一个regexp创建一个列表来获得结果,但我不明白如何应用这个regexp([^{]*?)\w(?=

我需要转换这个字符串

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

因为我有一个包含这些属性的列表。 比如说

a["foo"] = "home"
a["bar"] = "picture"
a["format"] = "jpg"
我试着做这样的事情

String.replace(a,"{",~s(#{))
但我犯了这个错误(

SyntaxError)iex:8:意外标记:)


我甚至尝试用一个regexp创建一个列表来获得结果,但我不明白如何应用这个regexp
([^{]*?)\w(?=\})

假设您想要字符串
“/home/picture.jpg”
作为结果,您可以使用
Regex.replace/3
作为替换函数:

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

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

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

"/home/picture.jpg"

在符号中使用大写字母
S

iex> a = "/{foo}/{bar}.{format}"
iex> IO.puts String.replace(a,"{",~S(#{))
/#{foo}/#{bar}.#{format}
此处解释了信号:

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