How to replace backslash

Hello,

For example, this one does not work:

julia> replace("foo  \spadbar{jjjd}","\\spad"=>"")
ERROR: ParseError:
# Error @ REPL[6]:1:21
ulia> replace("foo  \spadbar{jjjd}","\\spad"=>"")
#                   └┘ ── invalid escape sequence
Stacktrace:
 [1] top-level scope
   @ none:1

The first string is extracted from a database and contains some TeX like strings.

Regards,

Greg

I’m not sure I understand the question. Your error is getting thrown because it’s trying to parse \s as a special character (which doesn’t exist) when it creates the original string (long before it ever tries to call replace). You did the correct thing in your "\\spad", which is to escape the \ as \\.

What you have works fine if I use

julia> "foo  \spadbar{jjjd}" # original string is invalid
ERROR: ParseError:
# Error @ REPL[162]:1:7
"foo  \spadbar{jjjd}"
#     └┘ ── invalid escape sequence

julia> "foo  \\spadbar{jjjd}" # this might look like it has two backslashes
"foo  \\spadbar{jjjd}"

julia> println("foo  \\spadbar{jjjd}") # but printing reveals it only has one backslash
foo  \spadbar{jjjd}

julia> replace("foo  \\spadbar{jjjd}","\\spad"=>"") # with the backslash escape'd
"foo  bar{jjjd}"

julia> replace(raw"foo  \spadbar{jjjd}","\\spad"=>"") # use raw"" to take the string literally without escape characters
"foo  bar{jjjd}"

But if you’re extracting the string from a database then this should never have been a problem since it’s being read from a file/data rather than input (unless you’re using eval, Meta.parse, or something else you should avoid). So I’m not certain this resolves your issue.

4 Likes

Oh, excellent! And hello of course,

raw"string" is exactly what I was looking for. I did not remember it, and in this context ‘replace’ and not “print” it, I hadn’t thought about this. Many thanks.

About the database it’s an internal base and I use libbuila to call Julia from C. The extracted information contains some TeX-like constructs that were badly handled. Right now, I still need to remove some double quotes characters but that helped a lot i.e. let me go ahead.

Thanks again,

__
Greg

PS: BTW, from my tests, replace(“foo \spadbar{jjjd}”,“\spad”=>“”) does not work in my settings, the CAS interpreter/compiler I am working on uses ‘_’ as escape character and apparently mixing the two is relatively not handy, at least for me.