Hi so, the Regex
module supports named captures. Here’s an example from the docs for named_captures/3
, which extracts and prints all named captures in a match.
Regex.named_captures(~r/a(?<foo>b)c(?<bar>d)/, "abcd")
%{"bar" => "d", "foo" => "b"}
I’m using replace/4
to update some data. It allows replacing based on indexed groups (example below). For larger regexes that becomes very hard to manage, as there’ll likely be multiple captures moving around as the regex evolves. An approach using named captures will be more robust and more readable, but I didn’t find the syntax anywhere
# With indexed capture
Regex.replace(~r/\.(\d)$/, "500.5", ".\\g{1}0")
"500.50"
# With named capture
Regex.replace(~r/\.(?<my_capture>\d)$/, "500.5", ".\\g{my_capture}0")
** (MatchError) no match of right hand side value: {[], "my_capture}0"}
(elixir 1.15.0) lib/regex.ex:704: Regex.precompile_replacement/1
(elixir 1.15.0) lib/regex.ex:718: Regex.precompile_replacement/1
(elixir 1.15.0) lib/regex.ex:687: Regex.replace/4
At this point I’m wondering if replace
even supports that kind of substitution, hence the question.