Multiple regex replaces in one pass

Hi,

Is it possible to replace multiple regex patterns in a string in one pass? Basically, I want to combine the two replaces below into a single pass over the string

str |> String.replace(~r/^\s+/, "") |> String.replace(~r/\s+$/, ":")

I see https://hexdocs.pm/elixir/Regex.html#replace/4 has an optional function, but it looks like it’s not suitable for distinguishing between spaces at the beginning of the string and spaces at the end of the string.

While I don’t think you can do what you’re after in one regex, you can optimise a bit by using non-regex functions. For example:

str |> String.trim_leading() |> String.replace(~r/\s+$/, ":")

Although benchmarking this would still be a good idea. If the intent is that the final string always ends in an “:” then you could:

String.trim(str) <> ":"
3 Likes