2017-10-11 107 views
1

我需要這個字符串轉換在與string.replace藥劑

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

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

因爲我有這些屬性的列表。 例如

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

我嘗試這樣的事情

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

但我得到這個錯誤(

的SyntaxError)IEX:8:意外的標記:)

我嘗試了甚至一個正則表達式來創建一個List來嘗試獲得我的結果,但是我d on't明白我怎麼可以把這個正則表達式([^{]*?)\w(?=\})

回答

4

假設你想結果是該字符串"/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" 
+0

令人驚歎!這是我正在尋找的! – monkeyUser