gleam-lang / stdlib

🎁 Gleam's standard library
https://hexdocs.pm/gleam_stdlib/
Apache License 2.0
466 stars 168 forks source link

Consider adding a replace function to regex #621

Open fwgreen opened 4 months ago

fwgreen commented 4 months ago

My own naive implementation seems a bit slow with larger strings:

fn replace_all(
  regex: Result(Regex, CompileError),
  input: String,
  replacement: String,
) -> String {
  let assert Ok(re) = regex
  regex.split(re, input)
  |> string.join(replacement)
}

I'm hoping the target runtimes have something faster.

lpil commented 3 months ago

This is wanted! We've had a few PRs in the past but none of them were completed

apainintheneck commented 3 months ago

I took a quick look at this at it seems that there are native regex replace functions that should work for both JS and Erlang.

JS

The String.prototype.replace() or String.prototype.replaceAll() methods should work here. They both require that regexes have the global flag set and the external compile_regex method does that by default already.

https://github.com/gleam-lang/stdlib/blob/3ef0a879bff7e0f20407bd0279b88d7bec0a4cad/src/gleam_stdlib.mjs#L415

Erlang

The re:replace/4 method should do the trick. It will likely require specifying the global option though to make sure it replaces all occurrences.


This seems to be the most recent PR that tried to tackle this feature request.

lydell commented 1 week ago

Should this be closed since https://github.com/gleam-lang/stdlib/pull/638 was merged?