Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace with captured group in Julia

Tags:

regex

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

like image 860
tibL Avatar asked Mar 14 '18 11:03

tibL


2 Answers

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.

like image 140
niczky12 Avatar answered Nov 05 '22 12:11

niczky12


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.

like image 40
stej Avatar answered Nov 05 '22 14:11

stej