Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

The Problem: I often paste strings into Mathca which have many what I call "extender characters" --which may extend the character set." We know these have to be dealt with so Mathca can deal with the string without error.

Here is an example of such a string. The "extender characters" are the \ characters. (Happens to be a directory string pasted from W7.)

myString=
"C:\Users\NEW USER\Documents\Data Files General\Creative Write\Analysis incl Econ Trips etc\Write Econ Soc Chce Fin Trips\Mathca\Learn and How Tos\Projcts Apps Unoptimized\Gradebook12x3x12plus.nb"

Here is code which converts myString into something more clear to Mathca:

    FromCharacterCode[
       Insert[ToCharacterCode[
          myString],92,
          Position[ToCharacterCode[myString],92]]]  (* 92 is the ascii code of \ *)

The code works It replaces all "\" by "\\".
But it generates many "Unknown string escape" errors (warning that the \ characters in the string enable the extended character set, etc.)

There needs to be (there must be!) a function which permits us to optionally suppress the control character potentiality of certain characters. Then I would simply enter:

ConstrainedString[myString,{list of characters to optionally constrain}]

Then I could use

ReplaceAll[myConstrainedString, "\"->"\\"]

I don't want to be blindsided by extender characters not relevant in my code if, in that code, those characters only have the literal meaning. I want a clean way of converting or manipulating strings which have "extender characters", so a longer list of functions will be available.

share|improve this question
    
Shouldn't Mathematica offers to escape the pasted string for you? Like this. –  Silvia Jan 1 at 3:26
add comment

1 Answer

A somewhat simpler method would be to use StringReplace to change the single backslash \ into double backslashes \\. Each needs to be "escaped" (doubled) in order to work.

StringReplace[myString, "\\" -> "\\\\"]

It's not clear if this solves the "Unknown string escape" errors.

share|improve this answer
    
Why does each need to be escaped (doubled). I never thought of that... –  user11515 Jan 1 at 8:06
    
The backslash indicates that the next character is special. So to get an actual backslash inside the quote, you have to indicate that the backslash is actually a backslash (and not the special escape character), which is done by doubel-backslash. This is a particular example of an escape character en.wikipedia.org/wiki/Escape_character –  bill s Jan 1 at 15:29
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.