Reputation: 3404
Say I got a (possibly long) string containing matches for some regex. I would like to be able to call a non-trivial Julia function on all the matches and substitute the output in the string.
For example, let the regex be \|[0-9]+\|
and the computation function be f(x) = x^2
.
This is a string containing |1| and |4|.
I would like to obtain as a result
This is a string containing 1 and 16.
My question is: how can I implement this? Note that it would be nice if the code works for different regular expressions.
Upvotes: 2
Views: 241
Reputation: 69829
Just use the replace
function:
julia> s = "This is a string containing |1| and |4|."
"This is a string containing |1| and |4|."
julia> replace(s, r"\|[0-9]+\|" => x -> parse(Int, chop(x, head=1, tail=1)) ^ 2)
"This is a string containing 1 and 16."
In general in the signature of replace
that has the form:
replace(s::AbstractString, pat=>r; [count::Integer])
note that pat
can be a Regex
, and r
can be a function taking the match as an argument.
Upvotes: 4