New line in substitution string?

How does one put a new line (\n) in a substitution string? e.g.:

println(replace("test string", r"(test string)" => s"\1 \n line 2"))

Id like it to return:

test string
line 2

But I get:

Bad replacement string: \1 \n line 2

If I double escape the new line, I just get the escaped literal:

println(replace("test string", r"(test string)" => s"\1 \\n line 2"))
test string \n line 2

(Obviously toy example, I recognize not super motivated. But I have use case where I want to use group names (so need a substitution string) and new lines…)

Not sure you can do it with the syntactic sugar of s"...", but at least what you want can be achieved using the standard SubstitutionString constructor:

julia> println(replace("test string", r"(test string)" => SubstitutionString("\\1\nline 2")))
test string
line 2

ah, interesting. OK, thanks!

Can also be done with an actual newline inside a triple-quoted string:

julia> s"""1
       2""" == SubstitutionString("1\n2")
true
1 Like

I usually use the @s_str macro directly for this:

julia> println(replace("test string", r"(test string)" => @s_str("\\1\nline 2")))
test string
line 2
1 Like
1 Like

I use this code :
rapur*=string(:epoch," “, epoch,” “,accuracy(w,dtrn,predict),” “,
:tst,accuracy(w,dtst,predict)
,”\n")

output is : “epoch 0 0.06898333333333333 tst0.0717\nepoch 1 0.8966 tst0.9009\n”
How I can fixed this please.

(0): use backticks to separate your code

rapur = IOBuffer()
...
write(rapur, "epoch $epoch accuracy $(accuracy(w, darn, predict))")
...
rapur = String(take!(rapur))

Using a IOBuffer to create strings incrementally tends to be better than using *= repeatedly.