Remove \text generated by TeXForm

I need to remove all \text generated by TeXForm in Mathematica.

What I am doing now is this:

MyTeXForm[a_]:=StringReplace[ToString[TeXForm[a]], "\\text" -> ""]

But the result keeps the braces, for example: for a=fx,

the result of TeXForm[a] is \text{fx}

the result of MyTeXForm[a] is {fx}

But what I would like is it to be just fx


Solution 1:

You should be able to use string patterns. Based on http://reference.wolfram.com/mathematica/tutorial/StringPatterns.html, something like the following should work:

MyTeXForm[a_]:=StringReplace[ToString[TeXForm[a]], "\\text{"~~s___~~"}"->s]

I don't have Mathematica handy right now, but this should say 'Match "\text{" followed by zero or more characters that are stored in the variable s, followed by "}", then replace all of that with whatever is stored in s.'

UPDATE:

The above works in the simplest case of there being a single "\text{...}" element, but the pattern s___ is greedy, so on input a+bb+xx+y, which Mathematica's TeXForm renders as "a+\text{bb}+\text{xx}+y", it matches everything between the first "\text{" and last "}" --- so, "bb}+\text{xx" --- leading to the output

In[1]:= MyTeXForm[a+bb+xx+y]
Out[1]= a+bb}+\text{xx+y

A fix for this is to wrap the pattern with Shortest[], leading to a second definition

In[2]:= MyTeXForm2[a_] := StringReplace[
          ToString[TeXForm[a]],
          Shortest["\\text{" ~~ s___ ~~ "}"] -> s
        ]

which yields the output

In[3]:= MyTeXForm2[a+bb+xx+y]
Out[3]= a+bb+xx+y

as desired. Unfortunately this still won't work when the text itself contains a closing brace. For example, the input f["a}b","c}d"] (for some reason...) would give

In[4]:= MyTeXForm2[f["a}b","c}d"]]
Out[4]= f(a$\$b},c$\$d})

instead of "f(a$\}$b,c$\}$d)", which would be the proper processing of the TeXForm output "f(\text{a$\}$b},\text{c$\}$d})".