Given attrs:
attrs = %{
"name" => "Charlie Bucket",
"company" => "The Chocolate Factory",
"time" => "Aug 12, 2021",
"salesguy" => "Willy Wonka"
}
and an input string in source, a single call to Regex.replace can do this:
Regex.replace(~r/\[([^\]]+)\]/, source, fn _, key -> attrs[key] end)
This will silently replace unrecognized keys with empty strings; use something like Map.fetch if that isn’t desired.
The regex here looks worse than it is, because square brackets are metacharacters in regex:
\[matches a literal open bracket([^\]]+)captures one or more characters that aren’t a]\]matches a literal close bracket






















