New line in substitution string?


#1

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…)


#2

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

#3

ah, interesting. OK, thanks!


#4

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

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

#5

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

#6