( Update: Note the "." in the expression, this is most likely what causes the problem. )**
Starting point of my question is the following code, which works as expected:
StringReplace[#,RegularExpression[" id=\".*\""] -> ""] &["nilo id=\"jaap\" de roock"]
Above, we see a pure function which removes substrings of type id="foo bar" from a string.
I want to store the pure function as a key/value pair in an association ( which will be persisted to some medium eventually ). I have done this before and usually works as expected.
I usually do this as follows:
data = <|parser -> "code"|>;
where code represents the Mathematica code in question and if the code contains quotes (") then they are escaped as \".
A simple example of the procedure is the following:
"jaap" <> " en " <> "wim"
(* Out: "jaap en wim" *)
ass = <|"parser" -> "\"jaap\"<>\" en \"<> \"wim\""|>
(* Out: <|"parser" -> "jaap"<>" en "<> "wim"|> *)
ToExpression[ass["parser"]]
(* Out: "jaap en wim" *)
Now, when I apply this method to the code in question:
ass = <|"parser" -> ""|>
and attempt to insert the expression
StringReplace[#,RegularExpression[" id=\".*\""] -> ""] &["nilo id=\"jaap\" de roock"]
between the quotes where all quotes are escaped, Mathematica does not execute the command.
Like
"StringReplace[#,RegularExpression[\" id=\\".*\\ "\"]\[Rule]\"\"]&
No error is displayed but the dot is highlighted.
What have I done wrong? Is there an alternative?
Compress
andUncompress
instead ofToString
andToExpression
. That is not only more efficient, it will also cure the problems you are seeing. I think I better don't ask what you are trying to do, you have been warned that parsing html with regular expressions might not turn out to not be such a good idea, haven't you :-) $\endgroup$ToExpression["StringReplace[#,RegularExpression[\" id=\\\".*\\\"\"]\ \[Rule]\"\"]&"]
$\endgroup$