How Can I Handle String Containing "$" Symbol in Julia

I have extracted a substring from a file containing strings that starts with "$" and I want to replace the '$' symbol with "$" so that it looks like "\$sel:incPreTxn" and "\$!" as I will be later converting it to latex code. Please suggest me how can I handle "$" symbol in Julia.

I tried to use occursin and replace function that also didn't help and got LoadError. ERROR: LoadError: syntax: invalid interpolation syntax: "$""

Here is the sample code for reference:

str = "$sel:incPreTxn"
 if occursin("$", str)                   
     str = replace(str, "\$:" => "\\$")
 end

1 Answer

If I understood correctly you want to prefix the dollar sign that may be present in a string with a backslash symbol.

As the dollar symbol is "special" in Julia within a string (e.g. it allows interpolation of variables), you need to prefix it with a backlash in Julia too. And because the backlash is "special" too, you need to prefix it with a backlash as well.

This would do the job:

julia> str = "\$sel:incPreTxn"
"\$sel:incPreTxn"

julia> str2 = replace(str, "\$" => "\\\$")
"\\\$sel:incPreTxn"

While both str and str2 are displayed with 1 and 3 backslash, they are actually with 0 and 1 respectively, as you can see by printing them or saving them to a file:

julia> print(str)
$sel:incPreTxn
julia> println(str2)
\$sel:incPreTxn

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Robert Thorne

Robert Thorne

Automotive & Future Transportation Editor

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.

Share this article
Twitter Facebook Pinterest