如何替换的所有出现?与Elixir中的计数器串在一起



示例:"? ? ?"->"1 2 3"

似乎无法使用Regex.replace:

Regex.replace ~r/?/, "? ? ?", fn(token) -> ...some code here... end

因为没有办法拥有可变计数器。

你是对的,Regex中不能有可变计数器替换,所以你必须逐个递归地更改问号@JustMichael的回答看起来不错。如果问号之间除了空格之外还有其他东西,我会这样做:

def number_question_marks(string), do: number_question_marks("", string, 1)
#helper takes previous and current string
#if nothing changes we end recursion
def number_question_marks(string, string, _), do: string
#if something changed we call recursively
def number_question_marks(_previous, string, counter) do
  new = Regex.replace(~r/?/, string, inspect(counter), global: false)
  number_question_marks(string, new, counter + 1)
end
  "? ? ?" 
  |> String.split(" ") 
  |> Enum.map_reduce(1, fn(x, acc) -> {acc, acc + 1} end)
  |> elem(0)
  |> Enum.join(" ")

这是有效的,但我想还有一个更短的方法。

最新更新