tibL
tibL

Reputation: 297

Replace with captured group in Julia

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'.

Upvotes: 7

Views: 3515

Answers (2)

niczky12
niczky12

Reputation: 5063

A SubstitutionString can be created via s"". Similarly to how you'd create regexes with r"". These then can be used as a pair from => to to tell Julia how to replace matched strings.

Julia (1.8+)

julia> replace("hello #target# bye #target2#",  r"#(.+?)#" => s"captured:\1")
"hello captured:target bye captured:target2"

Older version:

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.

Upvotes: 16

stej
stej

Reputation: 29449

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.

Upvotes: 7

Related Questions