Regex.replace
You're seeing just the function
replace
, go back to Regex module for more information.
Specs
Receives a regex, a binary and a replacement, returns a new binary where all matches are replaced by the replacement.
The replacement can be either a string or a function. The string
is used as a replacement for every match and it allows specific
captures to be accessed via \N
or \g{N}
, where N
is the
capture. In case \0
is used, the whole match is inserted. Note
that in regexes the backslash needs to be escaped, hence in practice
you'll need to use \\N
and \\g{N}
.
When the replacement is a function, the function may have arity
N where each argument maps to a capture, with the first argument
being the whole match. If the function expects more arguments
than captures found, the remaining arguments will receive ""
.
Options
:global
- whenfalse
, replaces only the first occurrence (defaults totrue
)
Examples
iex> Regex.replace(~r/d/, "abc", "d")
"abc"
iex> Regex.replace(~r/b/, "abc", "d")
"adc"
iex> Regex.replace(~r/b/, "abc", "[\\0]")
"a[b]c"
iex> Regex.replace(~r/a(b|d)c/, "abcadc", "[\\1]")
"[b][d]"
iex> Regex.replace(~r/\.(\d)$/, "500.5", ".\\g{1}0")
"500.50"
iex> Regex.replace(~r/a(b|d)c/, "abcadc", fn _, x -> "[#{x}]" end)
"[b][d]"
iex> Regex.replace(~r/a/, "abcadc", "A", global: false)
"Abcadc"