简体   繁体   中英

How to replace all occurrences of ? in string with the counter in Elixir?

Example: "? ? ?" -> "1 2 3"

Seems like it can't be done with Regex.replace :

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

because there's no way to have a mutable counter.

You are right, you can't have mutable counter in Regex replace, so you will have to recursively change question marks one by one. @JustMichael answer looks nice. If there can be something other than spaces between question marks, I would do it this way:

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(" ")

It works but I guess there is a shorter way to do that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM