如何在Elixir中不使用插值实现字符串命名格式化?
Elixir 中实现命名占位符字符串格式化
纯 Elixir 实现(无需第三方库)
你可以通过正则匹配替换的方式实现类似 Ruby 的命名占位符格式化,完全依赖 Elixir 标准库:
# 从 CSV 解析得到的字符串列表 str = [ "Hello %{name}, do you come from %{country} ?", "Did %{name} just arrived from %{country} ?", "Today, %{name} will go to %{country}", "Today, %{name} will join us" ] # 待替换的键值数据 data = %{name: "Julio", country: "Nirvana"} # 定义格式化模块 defmodule StringFormatter do def format(str, data) do # 匹配 %{key} 格式的占位符,替换为对应值;无对应值则保留原占位符 Regex.replace(~r/%{(\w+)}/, str, fn _, key -> data |> Map.get(String.to_atom(key), "%{#{key}}") end) end end # 遍历处理并打印每个字符串 Enum.each(str, fn s -> s |> StringFormatter.format(data) |> IO.puts() end)
执行后输出:
Hello Julio, do you come from Nirvana ? Did Julio just arrived from Nirvana ? Today, Julio will go to Nirvana Today, Julio will join us
使用 Hex 库简化实现
如果你倾向于用成熟的第三方库,可以使用 fmt 库,它专门支持命名占位符格式化:
- 首先在
mix.exs中添加依赖:
defp deps do [ {:fmt, "~> 0.4.0"} ] end
- 执行
mix deps.get安装依赖后,即可使用:
str = [ "Hello %{name}, do you come from %{country} ?", "Did %{name} just arrived from %{country} ?", "Today, %{name} will go to %{country}", "Today, %{name} will join us" ] data = %{name: "Julio", country: "Nirvana"} Enum.each(str, fn s -> s |> Fmt.str(data) |> IO.puts() end)
这段代码会输出和纯 Elixir 实现完全一致的结果。
内容的提问来源于stack exchange,提问作者Kevin Tanudjaja
相关产品推荐
相关产品推荐

