How to convert a raw string to escape $

I have a situation where I am making a call to OpenAI and I get back a string, which might contain a $ like in “the price of the ticket is 10$”.

My problem is how to articulate the escape of the $ sign:

raw_string = r"the price of the ticket is 10$"
normal_string = replace(raw_string, r"$" => "\$")

is not working because it throws this error:

MethodError: no method matching similar(::Regex, ::Type{Any})

Closest candidates are:
  similar(!Matched::VSCodeServer.JuliaInterpreter.Compiled, ::Any)
   @ VSCodeServer ~/.vscode-server/extensions/julialang.language-julia-1.73.2/scripts/packages/JuliaInterpreter/src/types.jl:7
  similar(!Matched::LinearAlgebra.UpperHessenberg, ::Type{T}, !Matched::Tuple{Vararg{Int64, N}}) where {T, N}
   @ LinearAlgebra ~/.julia/juliaup/julia-1.10.0+0.x64.linux.gnu/share/julia/stdlib/v1.10/LinearAlgebra/src/hessenberg.jl:64
  similar(!Matched::LinearAlgebra.UpperHessenberg, ::Type{T}) where T
   @ LinearAlgebra ~/.julia/juliaup/julia-1.10.0+0.x64.linux.gnu/share/julia/stdlib/v1.10/LinearAlgebra/src/hessenberg.jl:63

 [1] _similar_or_copy(x::Regex, ::Type{Any})
   @ Base ./set.jl:572
 [2] replace(A::Regex, old_new::Pair{Regex, String}; count::Nothing)
   @ Base ./set.jl:690
 [3] replace(A::Regex, old_new::Pair{Regex, String})
   @ Base ./set.jl:686
 [4] top-level scope
   @ /mnt/data/projects/GenieGiano/test.ipynb:4

tbh I am kind of lost, I have tried many escape variations with more than one \, but nothing works… any help more than welcome!

The raw_string you create is not actually a raw string, it’s a Regex. To create a raw string, prepend the string with raw rather than r.

julia> r_string = r"the price of the ticket is 10$"
r"the price of the ticket is 10$"

julia> typeof(r_string)

julia> raw_string = raw"the price of the ticket is 10$"
"the price of the ticket is 10\$"

julia> println(raw_string)
the price of the ticket is 10$

Check the help entries for @r_str and @raw_str for more info.


thank you, it all makes sense now!

It’s not clear that you’ll have to do this.

julia> esc = "dollar-escaped \$ string"
"dollar-escaped \$ string"

julia> print(esc)
dollar-escaped $ string
julia> io = IOBuffer();

julia> write(io, esc)

julia> String(take!(io))
"dollar-escaped \$ string"

In other words, a string you get back from an API call will just have a $ in it, which is harmless on its own. It will print as \$ at the REPL, but if you run a replace on it, what you’ll have is:

julia> replace(esc, raw"$" => raw"\$")
"dollar-escaped \\\$ string"

Which might not be what you actually want.