I’m trying to use the replace
function, the doc specifies
replace(string::AbstractString, pat, r[, n::Integer=0])
Search for the given pattern pat, and replace each occurrence with r. If n is provided, replace at most n occurrences. As with search, the second argument may be a single character, a vector or a set of characters, a string, or a regular expression. If r is a function, each occurrence is replaced with r(s) where s is the matched substring. If pat is a regular expression and r is a SubstitutionString, then capture group references in r are replaced with the corresponding matched text.
I don’t understand the last sentence and couldn’t find SubstitutionString
(there is SubString
though, but I also couldn't directly find doc for that). I’d like to do a replace where r
uses the captured group(s) indicated in pat
. Something that corresponds to the following simple example in Python:
regex.sub(r'#(.+?)#', r"captured:\1", "hello #target# bye #target2#")
which returns 'hello captured:target bye captured:target2'
.
A SubstitutionString
can be created via s""
. Similarly to how you'd create regexes with r""
.
I guess this is what you're looking for:
julia> replace("hello #target# bye #target2#", r"#(.+?)#", s"captured:\1")
"hello captured:target bye captured:target2"
If you search for substitution string
in https://docs.julialang.org/en/v1/manual/strings/ you'll find another example there.
It has changed since last answer. Current correct version is this one
replace("first second", r"(\w+) (?<agroup>\w+)" => s"\g<agroup> \1")
replace("a", r"." => s"\g<0>1")
See https://docs.julialang.org/en/v1/manual/strings/ for more details.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With