New option for String.replace, occurrence

23 views
Skip to first unread message

Karlo Smid

unread,
Aug 12, 2025, 8:24:29 AMAug 12
to elixir-lang-core
Hi, I propose adding new key to option keyword list occurrence: n, where n is integer value of nth pattern occurrence in subject.
https://hexdocs.pm/elixir/String.html#replace/4

Example:
String.replace("a,b,c", ",", "-", occurrence: 2)
"a,b-c"

occurrence and global key should not be set together. In that case we should raise error.

Why this new feature? Regex does only support greedy and not greedy replace, but replace nth occurrence is not supported by Regex.
I needed this feature in advent of code 2015 day 19 task and it would also be useful in other cases of string parsing and manipulation.

Thank you.
Reply all
Reply to author
Forward
0 new messages