Trying to detect and replace strings that represent symbols is problematic. Essentially you need to parse the string as an expression to be robust, and that it better done with built-in parsing than with StringReplace.
Documentation for SymbolName says:
SymbolName always gives the short name, without any context.
Therefore you may use:
short =
Module[{T, SR = StringReplace[#, a__ ~~ "$" ~~ DigitCharacter .. :> a] &},
With[{ME = MakeExpression, U = Unevaluated},
ME @ #
/. s_Symbol :> T @ ME @ SR @ SymbolName @ U @ s
/. T@_@x_ :> x
/. _@x_ :> U@x ~ToString~ InputForm
]] &;
short @ "MyFunc[ShowIt[Q1`Private`var1$123], ShowIt[Q2`Private`var2$456], 0., 1.]"
"MyFunc[ShowIt[var1], ShowIt[var2], 0., 1.]"
short @ "MyFunc[ShowIt[\"Not`a`symbol\"], ShowIt[Q2`Private`var2$456], 0., 1.]"
"MyFunc[ShowIt[\"Not`a`symbol\"], ShowIt[var2], 0., 1.]"
Of course the string may change somewhat because of the parse and string conversion, much as doing Cell > Convert To... (form) does, but if this string is already automatically generated that should not be a problem.
Now that I have seen your application inside ShowIt it seems clear that you should avoid the conversion to a String in the first place.
Where you are using:
ExtactSymbolName[str_String]:=
With[{pat = WordCharacter},
StringReplace[str, (pat ... ~~ "`") .. ~~ s : pat .. ~~ ("$" ~~ NumberString) ... :> s]
];
ToExpression[ ExtactSymbolName @ ToString @ Unevaluated @ expr, InputForm, Defer]
I would use:
Module[{T, SR = StringReplace[#, a__ ~~ "$" ~~ DigitCharacter .. :> a] &},
Defer[expr]
/. s_Symbol :> T @ MakeExpression @ SR @ SymbolName @ Unevaluated @ s
/. T@_@x___ :> x
]
SymbolNameabout 2 months ago. :P – rcollyer Aug 20 '13 at 13:49