How can I replace every global instance of “x[2]” with “x_2”Translate in-line equations to TeX code (Any Package?)Automatic LaTeX parsing to replace text with macrosWhat is going wrong with this attempt to use global?How can I automatically replace subscripts and highlight GoTo labels?How to replace textHow can own commands be aware of global?How to do search-and-replace in a macro?how to use a global foreach?How to make NewDocumentCommand global?How to represent just space-character in replace stringreplace text with variables

How to be diplomatic in refusing to write code that breaches the privacy of our users

What can we do to stop prior company from asking us questions?

Is there a problem with hiding "forgot password" until it's needed?

Short story about space worker geeks who zone out by 'listening' to radiation from stars

System.debug(JSON.Serialize(o)) Not longer shows full string

Is `x >> pure y` equivalent to `liftM (const y) x`

Is this version of a gravity generator feasible?

Purchasing a ticket for someone else in another country?

What is the difference between "behavior" and "behaviour"?

Customer Requests (Sometimes) Drive Me Bonkers!

What Brexit proposals are on the table in the indicative votes on the 27th of March 2019?

Is HostGator storing my password in plaintext?

Italian words for tools

Opposite of a diet

How do I go from 300 unfinished/half written blog posts, to published posts?

How does the UK government determine the size of a mandate?

How many times can American Tourist re-enter UK in same 6 month period?

Fastening aluminum fascia to wooden subfascia

You cannot touch me, but I can touch you, who am I?

Why not increase contact surface when reentering the atmosphere?

What's the purpose of "true" in bash "if sudo true; then"

What does "I’d sit this one out, Cap," imply or mean in the context?

Why are there no referendums in the US?

Overloading istream>> to read comma-separated input



How can I replace every global instance of “x[2]” with “x_2”


Translate in-line equations to TeX code (Any Package?)Automatic LaTeX parsing to replace text with macrosWhat is going wrong with this attempt to use global?How can I automatically replace subscripts and highlight GoTo labels?How to replace textHow can own commands be aware of global?How to do search-and-replace in a macro?how to use a global foreach?How to make NewDocumentCommand global?How to represent just space-character in replace stringreplace text with variables













9















Thanks to Bruno for suggesting that for my specific case, where my results come from Mathematica, it's simply much easier to change the output in there using trivial replacement rules. However, this stands alone as a general question.



This is a slightly different question to what I've seen before, where I can use something like newcommandgagamma to make shortcuts of things using .



I have a series of LONG equations with stuff like x[2] or a[3] in them. I want to be able to always replace any instance of them with something else, like a command that takes a string and replaces it like something similar to



newcommandx[2]x_2



and



newcommanda[2]beta



Ideally, this would take account of the number inside, but I could easily just do it for all instances that arise. Any guidance would be great (my document class is Report)










share|improve this question
























  • Sort of sounds like translating math equations from one syntax to another, which reminded me of my very strange answer here: tex.stackexchange.com/questions/332012/…. Not that it will help you in the present case, without significant rework.

    – Steven B. Segletes
    yesterday






  • 2





    Do you absolutely need to convert as you typeset, or can you convert your source? If the latter, do you think it would be possible to unambiguously define all the situations in which this syntax would occur?

    – Chris H
    yesterday











  • @ChrisH that's exactly what I'm hoping for. I'm copying some parts of equations from Mathematica, and is written in terms of coefficients like x[2] for example, where I avoided subscripts in my code. I now want to save myself effort and simply define x[2] = x_2 in Latex, since it'll only ever occur within an equation.

    – Brad
    yesterday






  • 3





    My editor of choice supports regex find/replace so I'd simply find x[([0-9])] and replace with x_$1 (on a copy of course)

    – Chris H
    yesterday






  • 1





    @CarlWitthoft thank you for your comment. There are plenty of options for going about solving this, but just to keep everything localised within TeX I was looking for a somewhat simple method of achieving this, for applications even beyond this current issue. Alas, it has been solved now, and also in a multitude of methods. One could argue all night about which way is both, however, I certainly see no issue in solving it externally (which I happen to be doing now in Mathematica).

    – Brad
    8 hours ago















9















Thanks to Bruno for suggesting that for my specific case, where my results come from Mathematica, it's simply much easier to change the output in there using trivial replacement rules. However, this stands alone as a general question.



This is a slightly different question to what I've seen before, where I can use something like newcommandgagamma to make shortcuts of things using .



I have a series of LONG equations with stuff like x[2] or a[3] in them. I want to be able to always replace any instance of them with something else, like a command that takes a string and replaces it like something similar to



newcommandx[2]x_2



and



newcommanda[2]beta



Ideally, this would take account of the number inside, but I could easily just do it for all instances that arise. Any guidance would be great (my document class is Report)










share|improve this question
























  • Sort of sounds like translating math equations from one syntax to another, which reminded me of my very strange answer here: tex.stackexchange.com/questions/332012/…. Not that it will help you in the present case, without significant rework.

    – Steven B. Segletes
    yesterday






  • 2





    Do you absolutely need to convert as you typeset, or can you convert your source? If the latter, do you think it would be possible to unambiguously define all the situations in which this syntax would occur?

    – Chris H
    yesterday











  • @ChrisH that's exactly what I'm hoping for. I'm copying some parts of equations from Mathematica, and is written in terms of coefficients like x[2] for example, where I avoided subscripts in my code. I now want to save myself effort and simply define x[2] = x_2 in Latex, since it'll only ever occur within an equation.

    – Brad
    yesterday






  • 3





    My editor of choice supports regex find/replace so I'd simply find x[([0-9])] and replace with x_$1 (on a copy of course)

    – Chris H
    yesterday






  • 1





    @CarlWitthoft thank you for your comment. There are plenty of options for going about solving this, but just to keep everything localised within TeX I was looking for a somewhat simple method of achieving this, for applications even beyond this current issue. Alas, it has been solved now, and also in a multitude of methods. One could argue all night about which way is both, however, I certainly see no issue in solving it externally (which I happen to be doing now in Mathematica).

    – Brad
    8 hours ago













9












9








9








Thanks to Bruno for suggesting that for my specific case, where my results come from Mathematica, it's simply much easier to change the output in there using trivial replacement rules. However, this stands alone as a general question.



This is a slightly different question to what I've seen before, where I can use something like newcommandgagamma to make shortcuts of things using .



I have a series of LONG equations with stuff like x[2] or a[3] in them. I want to be able to always replace any instance of them with something else, like a command that takes a string and replaces it like something similar to



newcommandx[2]x_2



and



newcommanda[2]beta



Ideally, this would take account of the number inside, but I could easily just do it for all instances that arise. Any guidance would be great (my document class is Report)










share|improve this question
















Thanks to Bruno for suggesting that for my specific case, where my results come from Mathematica, it's simply much easier to change the output in there using trivial replacement rules. However, this stands alone as a general question.



This is a slightly different question to what I've seen before, where I can use something like newcommandgagamma to make shortcuts of things using .



I have a series of LONG equations with stuff like x[2] or a[3] in them. I want to be able to always replace any instance of them with something else, like a command that takes a string and replaces it like something similar to



newcommandx[2]x_2



and



newcommanda[2]beta



Ideally, this would take account of the number inside, but I could easily just do it for all instances that arise. Any guidance would be great (my document class is Report)







macros shorthands






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 10 hours ago







Brad

















asked yesterday









BradBrad

586




586












  • Sort of sounds like translating math equations from one syntax to another, which reminded me of my very strange answer here: tex.stackexchange.com/questions/332012/…. Not that it will help you in the present case, without significant rework.

    – Steven B. Segletes
    yesterday






  • 2





    Do you absolutely need to convert as you typeset, or can you convert your source? If the latter, do you think it would be possible to unambiguously define all the situations in which this syntax would occur?

    – Chris H
    yesterday











  • @ChrisH that's exactly what I'm hoping for. I'm copying some parts of equations from Mathematica, and is written in terms of coefficients like x[2] for example, where I avoided subscripts in my code. I now want to save myself effort and simply define x[2] = x_2 in Latex, since it'll only ever occur within an equation.

    – Brad
    yesterday






  • 3





    My editor of choice supports regex find/replace so I'd simply find x[([0-9])] and replace with x_$1 (on a copy of course)

    – Chris H
    yesterday






  • 1





    @CarlWitthoft thank you for your comment. There are plenty of options for going about solving this, but just to keep everything localised within TeX I was looking for a somewhat simple method of achieving this, for applications even beyond this current issue. Alas, it has been solved now, and also in a multitude of methods. One could argue all night about which way is both, however, I certainly see no issue in solving it externally (which I happen to be doing now in Mathematica).

    – Brad
    8 hours ago

















  • Sort of sounds like translating math equations from one syntax to another, which reminded me of my very strange answer here: tex.stackexchange.com/questions/332012/…. Not that it will help you in the present case, without significant rework.

    – Steven B. Segletes
    yesterday






  • 2





    Do you absolutely need to convert as you typeset, or can you convert your source? If the latter, do you think it would be possible to unambiguously define all the situations in which this syntax would occur?

    – Chris H
    yesterday











  • @ChrisH that's exactly what I'm hoping for. I'm copying some parts of equations from Mathematica, and is written in terms of coefficients like x[2] for example, where I avoided subscripts in my code. I now want to save myself effort and simply define x[2] = x_2 in Latex, since it'll only ever occur within an equation.

    – Brad
    yesterday






  • 3





    My editor of choice supports regex find/replace so I'd simply find x[([0-9])] and replace with x_$1 (on a copy of course)

    – Chris H
    yesterday






  • 1





    @CarlWitthoft thank you for your comment. There are plenty of options for going about solving this, but just to keep everything localised within TeX I was looking for a somewhat simple method of achieving this, for applications even beyond this current issue. Alas, it has been solved now, and also in a multitude of methods. One could argue all night about which way is both, however, I certainly see no issue in solving it externally (which I happen to be doing now in Mathematica).

    – Brad
    8 hours ago
















Sort of sounds like translating math equations from one syntax to another, which reminded me of my very strange answer here: tex.stackexchange.com/questions/332012/…. Not that it will help you in the present case, without significant rework.

– Steven B. Segletes
yesterday





Sort of sounds like translating math equations from one syntax to another, which reminded me of my very strange answer here: tex.stackexchange.com/questions/332012/…. Not that it will help you in the present case, without significant rework.

– Steven B. Segletes
yesterday




2




2





Do you absolutely need to convert as you typeset, or can you convert your source? If the latter, do you think it would be possible to unambiguously define all the situations in which this syntax would occur?

– Chris H
yesterday





Do you absolutely need to convert as you typeset, or can you convert your source? If the latter, do you think it would be possible to unambiguously define all the situations in which this syntax would occur?

– Chris H
yesterday













@ChrisH that's exactly what I'm hoping for. I'm copying some parts of equations from Mathematica, and is written in terms of coefficients like x[2] for example, where I avoided subscripts in my code. I now want to save myself effort and simply define x[2] = x_2 in Latex, since it'll only ever occur within an equation.

– Brad
yesterday





@ChrisH that's exactly what I'm hoping for. I'm copying some parts of equations from Mathematica, and is written in terms of coefficients like x[2] for example, where I avoided subscripts in my code. I now want to save myself effort and simply define x[2] = x_2 in Latex, since it'll only ever occur within an equation.

– Brad
yesterday




3




3





My editor of choice supports regex find/replace so I'd simply find x[([0-9])] and replace with x_$1 (on a copy of course)

– Chris H
yesterday





My editor of choice supports regex find/replace so I'd simply find x[([0-9])] and replace with x_$1 (on a copy of course)

– Chris H
yesterday




1




1





@CarlWitthoft thank you for your comment. There are plenty of options for going about solving this, but just to keep everything localised within TeX I was looking for a somewhat simple method of achieving this, for applications even beyond this current issue. Alas, it has been solved now, and also in a multitude of methods. One could argue all night about which way is both, however, I certainly see no issue in solving it externally (which I happen to be doing now in Mathematica).

– Brad
8 hours ago





@CarlWitthoft thank you for your comment. There are plenty of options for going about solving this, but just to keep everything localised within TeX I was looking for a somewhat simple method of achieving this, for applications even beyond this current issue. Alas, it has been solved now, and also in a multitude of methods. One could argue all night about which way is both, however, I certainly see no issue in solving it externally (which I happen to be doing now in Mathematica).

– Brad
8 hours ago










6 Answers
6






active

oldest

votes


















9














An extensible set of replacements:



documentclassarticle
usepackageamsmath
usepackagexparse

ExplSyntaxOn
NewDocumentCommandtransm

tl_set:Nn l__brad_trans_tl #1
regex_replace_all:nnN [(.*?)] csbcB1cE l__brad_trans_tl
regex_replace_all:nnN a calpha l__brad_trans_tl
% other replacements
% ...
% deliver the new token list
l__brad_trans_tl

ExplSyntaxOff

begindocument

$transx[1]+x[2]^2+a+a[3]$

enddocument


enter image description here






share|improve this answer


















  • 1





    Same comment as I made on David's answer. Yes, my l3regex is sometimes useful, but here the right solution by far is to do the replacements in Mathematica, not TeX.

    – Bruno Le Floch
    yesterday


















7














I really can not recommend doing this, but as you ask...



enter image description here



documentclassarticle

begindocument


mathcode`[="8000
mathcode`]="8000

catcode`[=active gdef[_bgroup
catcode`]=active gdef]egroup


hmmm
[
a[1]+a[2]+b[c+d[3]] + x
]

enddocument





share|improve this answer























  • Thank you for your answer - this is not quite what I'm after. But since this is not quite a conventional method, perhaps I am better simply going through and replacing things manually... I am moreso hoping to simply find a particular string and replace it with something else.

    – Brad
    yesterday











  • @Brad that really isn't how tex works:-) (unless you are using luatex)

    – David Carlisle
    yesterday











  • No worries at all! I have no problem sorting through everything, but I was hoping to save myself a bit of eyesight. Thank you for your help regardless!

    – Brad
    yesterday











  • @DavidCarlisle Come on, don't advocate crazy solutions to problems that can be trivially solved on the other side of the conversion. Brad should simply do the replacement in Mathematica.

    – Bruno Le Floch
    yesterday






  • 2





    @BrunoLeFloch I'd already said that in comments under the question, or just use perl or any other sane mechanism, but it's easy for you to see that this is beyond what's reasonable to do in tex as you know more than most on where tex's limits are, but I think it is still useful as a general rule to sketch how far you can get (and in particular what you can not reasonably do) in tex for this kind of question.

    – David Carlisle
    yesterday


















7














Inasmuch as I love doing crazy things in TeX, do the replacements in Mathematica! This will save you a huge amount of pain. For instance,



expr = (a[1] + a[2])/Sqrt[a[3]]
expr /. a[1] -> [Alpha], a[2] -> [Beta], a[3] -> [Gamma] // TeXForm


gives fracalpha +beta sqrtgamma with no need to tweak the output.






share|improve this answer























  • This is actually much more efficient than I realised! I was specifically trying to avid all those dirty symbols in my code but that's a much better overall solution. Big +1, thank you for the advice! I have edited my question to reflect this. I assume one would need to replace x[2] with the full subscript notation to achieve the $x_2$ necessary as well?

    – Brad
    10 hours ago












  • Yeah, it's just as easy to do the subscript replacements as well. Thank you for pointing this out Bruno; I will keep the answer above since I guess it does answer the specific question in particular, but I appreciate your solution greatly.

    – Brad
    9 hours ago


















5














Along the vein of my cited Translate in-line equations to TeX code (Any Package?), but a much simpler parsing request, I provide translate.



No catcode changes required. It will retain surrounding math style, etc.



documentclassarticle
usepackagelistofitems
newtokseqtoks
newcommandaddtoeqtoks[1]expandaftereqtoksexpandaftertheeqtoks#1
newcommandtranslate[1]%
setsepchar]%
readlistmyeqn#1%
eqtoks%
foreachitemxinmyeqn[]%
ifnumxcnt=1else%
if[myeqnsep[numexprxcnt-1]addtoeqtoks_bgroupfi%
if]myeqnsep[numexprxcnt-1]addtoeqtoksegroupfi%
fi%
expandafteraddtoeqtoksexpandafterx%
%
theeqtoks%

begindocument
[
translatea[1]+a[2]+b[c+d[3]] + x
]
enddocument


enter image description here






share|improve this answer






























    4














    For the sake of variety, here's a LuaLaTeX-based solution. It sets up a Lua function, called trans, which does most of the work with the help of Lua's versatile string-handling routines. The LaTeX macro trans is a wrapper that invokes the Lua function.



    enter image description here



    documentclassarticle
    usepackageluacode % for "luacode" environment and "luastringN" macro
    beginluacode


    function makesubscr ( s )
    s = s:gsub ( "(%b[])", function(x)
    return ( "_" .. string.sub ( x , 2 , -2 ) .. "" )
    end )
    if s:find ( "%b[]" ) then
    s = makesubscr ( s )
    end
    return s
    end
    function trans ( s )
    s = makesubscr ( s )
    s = s:gsub ( "a" , "\alpha" )
    s = s:gsub ( "b" , "\beta" )
    tex.sprint ( s )
    end


    endluacode

    %% TeX-side code
    newcommandtrans[1]directluatrans(luastringN#1)

    begindocument
    $transx[1]+x[2]^2+a+a[3]$

    $transa[1]+a[2]+b[c+d[3]]+x$
    enddocument





    share|improve this answer






























      2














      Here's a solution. The command addreplacementruletext-to-replacereplacement-text specifies replacements to make. Then the command replacesome math does the replacements.



      This would probably be better done with the l3regex package or really find and replace as many other people mentioned.



      documentclassarticle
      makeatletter
      newtoksri@activechars
      defaddreplacementrule#1#2addreplacementrule@#1@nil#2
      defaddreplacementrule@#1#2@nil#3%
      ri@activecharsexpandaftertheri@activechars\#1%
      ri@maketransitions#2@nil#1#3%


      defreplace#1%
      begingroup
      def\##1%
      bgrouplccode`~=`##1lowercaseegroup
      def~ri@continue##1%
      %
      catcode`##1=active
      %
      theri@activechars
      scantokens#1%
      endgroup


      defri@maketransitions#1#2@nil#3#4%
      deftemp#2%
      ifxtempempty
      expandafterdefcsname ri@lookup@detokenize#3#1endcsname#4%
      letnextrelax
      else
      expandafterdefcsname ri@lookup@detokenize#3#1endcsnameri@continue#3#1%
      defnextri@maketransitions#2@nil#3#1#4%
      fi
      next



      defri@continue#1#2%
      @ifundefinedri@lookup@detokenize#1#2%
      detokenize#1#2%
      %
      csname ri@lookup@detokenize#1#2endcsname
      %



      begindocument
      addreplacementrulex[2]x_2
      addreplacementrulex[3]x^2

      $x+1+x[2]+x[3]+x[1]$

      replace$x+1+x[2]+x[3]+x[1]$
      enddocument


      enter image description here






      share|improve this answer
























        Your Answer








        StackExchange.ready(function()
        var channelOptions =
        tags: "".split(" "),
        id: "85"
        ;
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function()
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled)
        StackExchange.using("snippets", function()
        createEditor();
        );

        else
        createEditor();

        );

        function createEditor()
        StackExchange.prepareEditor(
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: false,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: null,
        bindNavPrevention: true,
        postfix: "",
        imageUploader:
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        ,
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        );



        );













        draft saved

        draft discarded


















        StackExchange.ready(
        function ()
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2ftex.stackexchange.com%2fquestions%2f481546%2fhow-can-i-replace-every-global-instance-of-x2-with-x-2%23new-answer', 'question_page');

        );

        Post as a guest















        Required, but never shown

























        6 Answers
        6






        active

        oldest

        votes








        6 Answers
        6






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        9














        An extensible set of replacements:



        documentclassarticle
        usepackageamsmath
        usepackagexparse

        ExplSyntaxOn
        NewDocumentCommandtransm

        tl_set:Nn l__brad_trans_tl #1
        regex_replace_all:nnN [(.*?)] csbcB1cE l__brad_trans_tl
        regex_replace_all:nnN a calpha l__brad_trans_tl
        % other replacements
        % ...
        % deliver the new token list
        l__brad_trans_tl

        ExplSyntaxOff

        begindocument

        $transx[1]+x[2]^2+a+a[3]$

        enddocument


        enter image description here






        share|improve this answer


















        • 1





          Same comment as I made on David's answer. Yes, my l3regex is sometimes useful, but here the right solution by far is to do the replacements in Mathematica, not TeX.

          – Bruno Le Floch
          yesterday















        9














        An extensible set of replacements:



        documentclassarticle
        usepackageamsmath
        usepackagexparse

        ExplSyntaxOn
        NewDocumentCommandtransm

        tl_set:Nn l__brad_trans_tl #1
        regex_replace_all:nnN [(.*?)] csbcB1cE l__brad_trans_tl
        regex_replace_all:nnN a calpha l__brad_trans_tl
        % other replacements
        % ...
        % deliver the new token list
        l__brad_trans_tl

        ExplSyntaxOff

        begindocument

        $transx[1]+x[2]^2+a+a[3]$

        enddocument


        enter image description here






        share|improve this answer


















        • 1





          Same comment as I made on David's answer. Yes, my l3regex is sometimes useful, but here the right solution by far is to do the replacements in Mathematica, not TeX.

          – Bruno Le Floch
          yesterday













        9












        9








        9







        An extensible set of replacements:



        documentclassarticle
        usepackageamsmath
        usepackagexparse

        ExplSyntaxOn
        NewDocumentCommandtransm

        tl_set:Nn l__brad_trans_tl #1
        regex_replace_all:nnN [(.*?)] csbcB1cE l__brad_trans_tl
        regex_replace_all:nnN a calpha l__brad_trans_tl
        % other replacements
        % ...
        % deliver the new token list
        l__brad_trans_tl

        ExplSyntaxOff

        begindocument

        $transx[1]+x[2]^2+a+a[3]$

        enddocument


        enter image description here






        share|improve this answer













        An extensible set of replacements:



        documentclassarticle
        usepackageamsmath
        usepackagexparse

        ExplSyntaxOn
        NewDocumentCommandtransm

        tl_set:Nn l__brad_trans_tl #1
        regex_replace_all:nnN [(.*?)] csbcB1cE l__brad_trans_tl
        regex_replace_all:nnN a calpha l__brad_trans_tl
        % other replacements
        % ...
        % deliver the new token list
        l__brad_trans_tl

        ExplSyntaxOff

        begindocument

        $transx[1]+x[2]^2+a+a[3]$

        enddocument


        enter image description here







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered yesterday









        egregegreg

        729k8819273240




        729k8819273240







        • 1





          Same comment as I made on David's answer. Yes, my l3regex is sometimes useful, but here the right solution by far is to do the replacements in Mathematica, not TeX.

          – Bruno Le Floch
          yesterday












        • 1





          Same comment as I made on David's answer. Yes, my l3regex is sometimes useful, but here the right solution by far is to do the replacements in Mathematica, not TeX.

          – Bruno Le Floch
          yesterday







        1




        1





        Same comment as I made on David's answer. Yes, my l3regex is sometimes useful, but here the right solution by far is to do the replacements in Mathematica, not TeX.

        – Bruno Le Floch
        yesterday





        Same comment as I made on David's answer. Yes, my l3regex is sometimes useful, but here the right solution by far is to do the replacements in Mathematica, not TeX.

        – Bruno Le Floch
        yesterday











        7














        I really can not recommend doing this, but as you ask...



        enter image description here



        documentclassarticle

        begindocument


        mathcode`[="8000
        mathcode`]="8000

        catcode`[=active gdef[_bgroup
        catcode`]=active gdef]egroup


        hmmm
        [
        a[1]+a[2]+b[c+d[3]] + x
        ]

        enddocument





        share|improve this answer























        • Thank you for your answer - this is not quite what I'm after. But since this is not quite a conventional method, perhaps I am better simply going through and replacing things manually... I am moreso hoping to simply find a particular string and replace it with something else.

          – Brad
          yesterday











        • @Brad that really isn't how tex works:-) (unless you are using luatex)

          – David Carlisle
          yesterday











        • No worries at all! I have no problem sorting through everything, but I was hoping to save myself a bit of eyesight. Thank you for your help regardless!

          – Brad
          yesterday











        • @DavidCarlisle Come on, don't advocate crazy solutions to problems that can be trivially solved on the other side of the conversion. Brad should simply do the replacement in Mathematica.

          – Bruno Le Floch
          yesterday






        • 2





          @BrunoLeFloch I'd already said that in comments under the question, or just use perl or any other sane mechanism, but it's easy for you to see that this is beyond what's reasonable to do in tex as you know more than most on where tex's limits are, but I think it is still useful as a general rule to sketch how far you can get (and in particular what you can not reasonably do) in tex for this kind of question.

          – David Carlisle
          yesterday















        7














        I really can not recommend doing this, but as you ask...



        enter image description here



        documentclassarticle

        begindocument


        mathcode`[="8000
        mathcode`]="8000

        catcode`[=active gdef[_bgroup
        catcode`]=active gdef]egroup


        hmmm
        [
        a[1]+a[2]+b[c+d[3]] + x
        ]

        enddocument





        share|improve this answer























        • Thank you for your answer - this is not quite what I'm after. But since this is not quite a conventional method, perhaps I am better simply going through and replacing things manually... I am moreso hoping to simply find a particular string and replace it with something else.

          – Brad
          yesterday











        • @Brad that really isn't how tex works:-) (unless you are using luatex)

          – David Carlisle
          yesterday











        • No worries at all! I have no problem sorting through everything, but I was hoping to save myself a bit of eyesight. Thank you for your help regardless!

          – Brad
          yesterday











        • @DavidCarlisle Come on, don't advocate crazy solutions to problems that can be trivially solved on the other side of the conversion. Brad should simply do the replacement in Mathematica.

          – Bruno Le Floch
          yesterday






        • 2





          @BrunoLeFloch I'd already said that in comments under the question, or just use perl or any other sane mechanism, but it's easy for you to see that this is beyond what's reasonable to do in tex as you know more than most on where tex's limits are, but I think it is still useful as a general rule to sketch how far you can get (and in particular what you can not reasonably do) in tex for this kind of question.

          – David Carlisle
          yesterday













        7












        7








        7







        I really can not recommend doing this, but as you ask...



        enter image description here



        documentclassarticle

        begindocument


        mathcode`[="8000
        mathcode`]="8000

        catcode`[=active gdef[_bgroup
        catcode`]=active gdef]egroup


        hmmm
        [
        a[1]+a[2]+b[c+d[3]] + x
        ]

        enddocument





        share|improve this answer













        I really can not recommend doing this, but as you ask...



        enter image description here



        documentclassarticle

        begindocument


        mathcode`[="8000
        mathcode`]="8000

        catcode`[=active gdef[_bgroup
        catcode`]=active gdef]egroup


        hmmm
        [
        a[1]+a[2]+b[c+d[3]] + x
        ]

        enddocument






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered yesterday









        David CarlisleDavid Carlisle

        496k4111431890




        496k4111431890












        • Thank you for your answer - this is not quite what I'm after. But since this is not quite a conventional method, perhaps I am better simply going through and replacing things manually... I am moreso hoping to simply find a particular string and replace it with something else.

          – Brad
          yesterday











        • @Brad that really isn't how tex works:-) (unless you are using luatex)

          – David Carlisle
          yesterday











        • No worries at all! I have no problem sorting through everything, but I was hoping to save myself a bit of eyesight. Thank you for your help regardless!

          – Brad
          yesterday











        • @DavidCarlisle Come on, don't advocate crazy solutions to problems that can be trivially solved on the other side of the conversion. Brad should simply do the replacement in Mathematica.

          – Bruno Le Floch
          yesterday






        • 2





          @BrunoLeFloch I'd already said that in comments under the question, or just use perl or any other sane mechanism, but it's easy for you to see that this is beyond what's reasonable to do in tex as you know more than most on where tex's limits are, but I think it is still useful as a general rule to sketch how far you can get (and in particular what you can not reasonably do) in tex for this kind of question.

          – David Carlisle
          yesterday

















        • Thank you for your answer - this is not quite what I'm after. But since this is not quite a conventional method, perhaps I am better simply going through and replacing things manually... I am moreso hoping to simply find a particular string and replace it with something else.

          – Brad
          yesterday











        • @Brad that really isn't how tex works:-) (unless you are using luatex)

          – David Carlisle
          yesterday











        • No worries at all! I have no problem sorting through everything, but I was hoping to save myself a bit of eyesight. Thank you for your help regardless!

          – Brad
          yesterday











        • @DavidCarlisle Come on, don't advocate crazy solutions to problems that can be trivially solved on the other side of the conversion. Brad should simply do the replacement in Mathematica.

          – Bruno Le Floch
          yesterday






        • 2





          @BrunoLeFloch I'd already said that in comments under the question, or just use perl or any other sane mechanism, but it's easy for you to see that this is beyond what's reasonable to do in tex as you know more than most on where tex's limits are, but I think it is still useful as a general rule to sketch how far you can get (and in particular what you can not reasonably do) in tex for this kind of question.

          – David Carlisle
          yesterday
















        Thank you for your answer - this is not quite what I'm after. But since this is not quite a conventional method, perhaps I am better simply going through and replacing things manually... I am moreso hoping to simply find a particular string and replace it with something else.

        – Brad
        yesterday





        Thank you for your answer - this is not quite what I'm after. But since this is not quite a conventional method, perhaps I am better simply going through and replacing things manually... I am moreso hoping to simply find a particular string and replace it with something else.

        – Brad
        yesterday













        @Brad that really isn't how tex works:-) (unless you are using luatex)

        – David Carlisle
        yesterday





        @Brad that really isn't how tex works:-) (unless you are using luatex)

        – David Carlisle
        yesterday













        No worries at all! I have no problem sorting through everything, but I was hoping to save myself a bit of eyesight. Thank you for your help regardless!

        – Brad
        yesterday





        No worries at all! I have no problem sorting through everything, but I was hoping to save myself a bit of eyesight. Thank you for your help regardless!

        – Brad
        yesterday













        @DavidCarlisle Come on, don't advocate crazy solutions to problems that can be trivially solved on the other side of the conversion. Brad should simply do the replacement in Mathematica.

        – Bruno Le Floch
        yesterday





        @DavidCarlisle Come on, don't advocate crazy solutions to problems that can be trivially solved on the other side of the conversion. Brad should simply do the replacement in Mathematica.

        – Bruno Le Floch
        yesterday




        2




        2





        @BrunoLeFloch I'd already said that in comments under the question, or just use perl or any other sane mechanism, but it's easy for you to see that this is beyond what's reasonable to do in tex as you know more than most on where tex's limits are, but I think it is still useful as a general rule to sketch how far you can get (and in particular what you can not reasonably do) in tex for this kind of question.

        – David Carlisle
        yesterday





        @BrunoLeFloch I'd already said that in comments under the question, or just use perl or any other sane mechanism, but it's easy for you to see that this is beyond what's reasonable to do in tex as you know more than most on where tex's limits are, but I think it is still useful as a general rule to sketch how far you can get (and in particular what you can not reasonably do) in tex for this kind of question.

        – David Carlisle
        yesterday











        7














        Inasmuch as I love doing crazy things in TeX, do the replacements in Mathematica! This will save you a huge amount of pain. For instance,



        expr = (a[1] + a[2])/Sqrt[a[3]]
        expr /. a[1] -> [Alpha], a[2] -> [Beta], a[3] -> [Gamma] // TeXForm


        gives fracalpha +beta sqrtgamma with no need to tweak the output.






        share|improve this answer























        • This is actually much more efficient than I realised! I was specifically trying to avid all those dirty symbols in my code but that's a much better overall solution. Big +1, thank you for the advice! I have edited my question to reflect this. I assume one would need to replace x[2] with the full subscript notation to achieve the $x_2$ necessary as well?

          – Brad
          10 hours ago












        • Yeah, it's just as easy to do the subscript replacements as well. Thank you for pointing this out Bruno; I will keep the answer above since I guess it does answer the specific question in particular, but I appreciate your solution greatly.

          – Brad
          9 hours ago















        7














        Inasmuch as I love doing crazy things in TeX, do the replacements in Mathematica! This will save you a huge amount of pain. For instance,



        expr = (a[1] + a[2])/Sqrt[a[3]]
        expr /. a[1] -> [Alpha], a[2] -> [Beta], a[3] -> [Gamma] // TeXForm


        gives fracalpha +beta sqrtgamma with no need to tweak the output.






        share|improve this answer























        • This is actually much more efficient than I realised! I was specifically trying to avid all those dirty symbols in my code but that's a much better overall solution. Big +1, thank you for the advice! I have edited my question to reflect this. I assume one would need to replace x[2] with the full subscript notation to achieve the $x_2$ necessary as well?

          – Brad
          10 hours ago












        • Yeah, it's just as easy to do the subscript replacements as well. Thank you for pointing this out Bruno; I will keep the answer above since I guess it does answer the specific question in particular, but I appreciate your solution greatly.

          – Brad
          9 hours ago













        7












        7








        7







        Inasmuch as I love doing crazy things in TeX, do the replacements in Mathematica! This will save you a huge amount of pain. For instance,



        expr = (a[1] + a[2])/Sqrt[a[3]]
        expr /. a[1] -> [Alpha], a[2] -> [Beta], a[3] -> [Gamma] // TeXForm


        gives fracalpha +beta sqrtgamma with no need to tweak the output.






        share|improve this answer













        Inasmuch as I love doing crazy things in TeX, do the replacements in Mathematica! This will save you a huge amount of pain. For instance,



        expr = (a[1] + a[2])/Sqrt[a[3]]
        expr /. a[1] -> [Alpha], a[2] -> [Beta], a[3] -> [Gamma] // TeXForm


        gives fracalpha +beta sqrtgamma with no need to tweak the output.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered yesterday









        Bruno Le FlochBruno Le Floch

        34.2k5115211




        34.2k5115211












        • This is actually much more efficient than I realised! I was specifically trying to avid all those dirty symbols in my code but that's a much better overall solution. Big +1, thank you for the advice! I have edited my question to reflect this. I assume one would need to replace x[2] with the full subscript notation to achieve the $x_2$ necessary as well?

          – Brad
          10 hours ago












        • Yeah, it's just as easy to do the subscript replacements as well. Thank you for pointing this out Bruno; I will keep the answer above since I guess it does answer the specific question in particular, but I appreciate your solution greatly.

          – Brad
          9 hours ago

















        • This is actually much more efficient than I realised! I was specifically trying to avid all those dirty symbols in my code but that's a much better overall solution. Big +1, thank you for the advice! I have edited my question to reflect this. I assume one would need to replace x[2] with the full subscript notation to achieve the $x_2$ necessary as well?

          – Brad
          10 hours ago












        • Yeah, it's just as easy to do the subscript replacements as well. Thank you for pointing this out Bruno; I will keep the answer above since I guess it does answer the specific question in particular, but I appreciate your solution greatly.

          – Brad
          9 hours ago
















        This is actually much more efficient than I realised! I was specifically trying to avid all those dirty symbols in my code but that's a much better overall solution. Big +1, thank you for the advice! I have edited my question to reflect this. I assume one would need to replace x[2] with the full subscript notation to achieve the $x_2$ necessary as well?

        – Brad
        10 hours ago






        This is actually much more efficient than I realised! I was specifically trying to avid all those dirty symbols in my code but that's a much better overall solution. Big +1, thank you for the advice! I have edited my question to reflect this. I assume one would need to replace x[2] with the full subscript notation to achieve the $x_2$ necessary as well?

        – Brad
        10 hours ago














        Yeah, it's just as easy to do the subscript replacements as well. Thank you for pointing this out Bruno; I will keep the answer above since I guess it does answer the specific question in particular, but I appreciate your solution greatly.

        – Brad
        9 hours ago





        Yeah, it's just as easy to do the subscript replacements as well. Thank you for pointing this out Bruno; I will keep the answer above since I guess it does answer the specific question in particular, but I appreciate your solution greatly.

        – Brad
        9 hours ago











        5














        Along the vein of my cited Translate in-line equations to TeX code (Any Package?), but a much simpler parsing request, I provide translate.



        No catcode changes required. It will retain surrounding math style, etc.



        documentclassarticle
        usepackagelistofitems
        newtokseqtoks
        newcommandaddtoeqtoks[1]expandaftereqtoksexpandaftertheeqtoks#1
        newcommandtranslate[1]%
        setsepchar]%
        readlistmyeqn#1%
        eqtoks%
        foreachitemxinmyeqn[]%
        ifnumxcnt=1else%
        if[myeqnsep[numexprxcnt-1]addtoeqtoks_bgroupfi%
        if]myeqnsep[numexprxcnt-1]addtoeqtoksegroupfi%
        fi%
        expandafteraddtoeqtoksexpandafterx%
        %
        theeqtoks%

        begindocument
        [
        translatea[1]+a[2]+b[c+d[3]] + x
        ]
        enddocument


        enter image description here






        share|improve this answer



























          5














          Along the vein of my cited Translate in-line equations to TeX code (Any Package?), but a much simpler parsing request, I provide translate.



          No catcode changes required. It will retain surrounding math style, etc.



          documentclassarticle
          usepackagelistofitems
          newtokseqtoks
          newcommandaddtoeqtoks[1]expandaftereqtoksexpandaftertheeqtoks#1
          newcommandtranslate[1]%
          setsepchar]%
          readlistmyeqn#1%
          eqtoks%
          foreachitemxinmyeqn[]%
          ifnumxcnt=1else%
          if[myeqnsep[numexprxcnt-1]addtoeqtoks_bgroupfi%
          if]myeqnsep[numexprxcnt-1]addtoeqtoksegroupfi%
          fi%
          expandafteraddtoeqtoksexpandafterx%
          %
          theeqtoks%

          begindocument
          [
          translatea[1]+a[2]+b[c+d[3]] + x
          ]
          enddocument


          enter image description here






          share|improve this answer

























            5












            5








            5







            Along the vein of my cited Translate in-line equations to TeX code (Any Package?), but a much simpler parsing request, I provide translate.



            No catcode changes required. It will retain surrounding math style, etc.



            documentclassarticle
            usepackagelistofitems
            newtokseqtoks
            newcommandaddtoeqtoks[1]expandaftereqtoksexpandaftertheeqtoks#1
            newcommandtranslate[1]%
            setsepchar]%
            readlistmyeqn#1%
            eqtoks%
            foreachitemxinmyeqn[]%
            ifnumxcnt=1else%
            if[myeqnsep[numexprxcnt-1]addtoeqtoks_bgroupfi%
            if]myeqnsep[numexprxcnt-1]addtoeqtoksegroupfi%
            fi%
            expandafteraddtoeqtoksexpandafterx%
            %
            theeqtoks%

            begindocument
            [
            translatea[1]+a[2]+b[c+d[3]] + x
            ]
            enddocument


            enter image description here






            share|improve this answer













            Along the vein of my cited Translate in-line equations to TeX code (Any Package?), but a much simpler parsing request, I provide translate.



            No catcode changes required. It will retain surrounding math style, etc.



            documentclassarticle
            usepackagelistofitems
            newtokseqtoks
            newcommandaddtoeqtoks[1]expandaftereqtoksexpandaftertheeqtoks#1
            newcommandtranslate[1]%
            setsepchar]%
            readlistmyeqn#1%
            eqtoks%
            foreachitemxinmyeqn[]%
            ifnumxcnt=1else%
            if[myeqnsep[numexprxcnt-1]addtoeqtoks_bgroupfi%
            if]myeqnsep[numexprxcnt-1]addtoeqtoksegroupfi%
            fi%
            expandafteraddtoeqtoksexpandafterx%
            %
            theeqtoks%

            begindocument
            [
            translatea[1]+a[2]+b[c+d[3]] + x
            ]
            enddocument


            enter image description here







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered yesterday









            Steven B. SegletesSteven B. Segletes

            159k9204413




            159k9204413





















                4














                For the sake of variety, here's a LuaLaTeX-based solution. It sets up a Lua function, called trans, which does most of the work with the help of Lua's versatile string-handling routines. The LaTeX macro trans is a wrapper that invokes the Lua function.



                enter image description here



                documentclassarticle
                usepackageluacode % for "luacode" environment and "luastringN" macro
                beginluacode


                function makesubscr ( s )
                s = s:gsub ( "(%b[])", function(x)
                return ( "_" .. string.sub ( x , 2 , -2 ) .. "" )
                end )
                if s:find ( "%b[]" ) then
                s = makesubscr ( s )
                end
                return s
                end
                function trans ( s )
                s = makesubscr ( s )
                s = s:gsub ( "a" , "\alpha" )
                s = s:gsub ( "b" , "\beta" )
                tex.sprint ( s )
                end


                endluacode

                %% TeX-side code
                newcommandtrans[1]directluatrans(luastringN#1)

                begindocument
                $transx[1]+x[2]^2+a+a[3]$

                $transa[1]+a[2]+b[c+d[3]]+x$
                enddocument





                share|improve this answer



























                  4














                  For the sake of variety, here's a LuaLaTeX-based solution. It sets up a Lua function, called trans, which does most of the work with the help of Lua's versatile string-handling routines. The LaTeX macro trans is a wrapper that invokes the Lua function.



                  enter image description here



                  documentclassarticle
                  usepackageluacode % for "luacode" environment and "luastringN" macro
                  beginluacode


                  function makesubscr ( s )
                  s = s:gsub ( "(%b[])", function(x)
                  return ( "_" .. string.sub ( x , 2 , -2 ) .. "" )
                  end )
                  if s:find ( "%b[]" ) then
                  s = makesubscr ( s )
                  end
                  return s
                  end
                  function trans ( s )
                  s = makesubscr ( s )
                  s = s:gsub ( "a" , "\alpha" )
                  s = s:gsub ( "b" , "\beta" )
                  tex.sprint ( s )
                  end


                  endluacode

                  %% TeX-side code
                  newcommandtrans[1]directluatrans(luastringN#1)

                  begindocument
                  $transx[1]+x[2]^2+a+a[3]$

                  $transa[1]+a[2]+b[c+d[3]]+x$
                  enddocument





                  share|improve this answer

























                    4












                    4








                    4







                    For the sake of variety, here's a LuaLaTeX-based solution. It sets up a Lua function, called trans, which does most of the work with the help of Lua's versatile string-handling routines. The LaTeX macro trans is a wrapper that invokes the Lua function.



                    enter image description here



                    documentclassarticle
                    usepackageluacode % for "luacode" environment and "luastringN" macro
                    beginluacode


                    function makesubscr ( s )
                    s = s:gsub ( "(%b[])", function(x)
                    return ( "_" .. string.sub ( x , 2 , -2 ) .. "" )
                    end )
                    if s:find ( "%b[]" ) then
                    s = makesubscr ( s )
                    end
                    return s
                    end
                    function trans ( s )
                    s = makesubscr ( s )
                    s = s:gsub ( "a" , "\alpha" )
                    s = s:gsub ( "b" , "\beta" )
                    tex.sprint ( s )
                    end


                    endluacode

                    %% TeX-side code
                    newcommandtrans[1]directluatrans(luastringN#1)

                    begindocument
                    $transx[1]+x[2]^2+a+a[3]$

                    $transa[1]+a[2]+b[c+d[3]]+x$
                    enddocument





                    share|improve this answer













                    For the sake of variety, here's a LuaLaTeX-based solution. It sets up a Lua function, called trans, which does most of the work with the help of Lua's versatile string-handling routines. The LaTeX macro trans is a wrapper that invokes the Lua function.



                    enter image description here



                    documentclassarticle
                    usepackageluacode % for "luacode" environment and "luastringN" macro
                    beginluacode


                    function makesubscr ( s )
                    s = s:gsub ( "(%b[])", function(x)
                    return ( "_" .. string.sub ( x , 2 , -2 ) .. "" )
                    end )
                    if s:find ( "%b[]" ) then
                    s = makesubscr ( s )
                    end
                    return s
                    end
                    function trans ( s )
                    s = makesubscr ( s )
                    s = s:gsub ( "a" , "\alpha" )
                    s = s:gsub ( "b" , "\beta" )
                    tex.sprint ( s )
                    end


                    endluacode

                    %% TeX-side code
                    newcommandtrans[1]directluatrans(luastringN#1)

                    begindocument
                    $transx[1]+x[2]^2+a+a[3]$

                    $transa[1]+a[2]+b[c+d[3]]+x$
                    enddocument






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered 14 hours ago









                    MicoMico

                    284k31388778




                    284k31388778





















                        2














                        Here's a solution. The command addreplacementruletext-to-replacereplacement-text specifies replacements to make. Then the command replacesome math does the replacements.



                        This would probably be better done with the l3regex package or really find and replace as many other people mentioned.



                        documentclassarticle
                        makeatletter
                        newtoksri@activechars
                        defaddreplacementrule#1#2addreplacementrule@#1@nil#2
                        defaddreplacementrule@#1#2@nil#3%
                        ri@activecharsexpandaftertheri@activechars\#1%
                        ri@maketransitions#2@nil#1#3%


                        defreplace#1%
                        begingroup
                        def\##1%
                        bgrouplccode`~=`##1lowercaseegroup
                        def~ri@continue##1%
                        %
                        catcode`##1=active
                        %
                        theri@activechars
                        scantokens#1%
                        endgroup


                        defri@maketransitions#1#2@nil#3#4%
                        deftemp#2%
                        ifxtempempty
                        expandafterdefcsname ri@lookup@detokenize#3#1endcsname#4%
                        letnextrelax
                        else
                        expandafterdefcsname ri@lookup@detokenize#3#1endcsnameri@continue#3#1%
                        defnextri@maketransitions#2@nil#3#1#4%
                        fi
                        next



                        defri@continue#1#2%
                        @ifundefinedri@lookup@detokenize#1#2%
                        detokenize#1#2%
                        %
                        csname ri@lookup@detokenize#1#2endcsname
                        %



                        begindocument
                        addreplacementrulex[2]x_2
                        addreplacementrulex[3]x^2

                        $x+1+x[2]+x[3]+x[1]$

                        replace$x+1+x[2]+x[3]+x[1]$
                        enddocument


                        enter image description here






                        share|improve this answer





























                          2














                          Here's a solution. The command addreplacementruletext-to-replacereplacement-text specifies replacements to make. Then the command replacesome math does the replacements.



                          This would probably be better done with the l3regex package or really find and replace as many other people mentioned.



                          documentclassarticle
                          makeatletter
                          newtoksri@activechars
                          defaddreplacementrule#1#2addreplacementrule@#1@nil#2
                          defaddreplacementrule@#1#2@nil#3%
                          ri@activecharsexpandaftertheri@activechars\#1%
                          ri@maketransitions#2@nil#1#3%


                          defreplace#1%
                          begingroup
                          def\##1%
                          bgrouplccode`~=`##1lowercaseegroup
                          def~ri@continue##1%
                          %
                          catcode`##1=active
                          %
                          theri@activechars
                          scantokens#1%
                          endgroup


                          defri@maketransitions#1#2@nil#3#4%
                          deftemp#2%
                          ifxtempempty
                          expandafterdefcsname ri@lookup@detokenize#3#1endcsname#4%
                          letnextrelax
                          else
                          expandafterdefcsname ri@lookup@detokenize#3#1endcsnameri@continue#3#1%
                          defnextri@maketransitions#2@nil#3#1#4%
                          fi
                          next



                          defri@continue#1#2%
                          @ifundefinedri@lookup@detokenize#1#2%
                          detokenize#1#2%
                          %
                          csname ri@lookup@detokenize#1#2endcsname
                          %



                          begindocument
                          addreplacementrulex[2]x_2
                          addreplacementrulex[3]x^2

                          $x+1+x[2]+x[3]+x[1]$

                          replace$x+1+x[2]+x[3]+x[1]$
                          enddocument


                          enter image description here






                          share|improve this answer



























                            2












                            2








                            2







                            Here's a solution. The command addreplacementruletext-to-replacereplacement-text specifies replacements to make. Then the command replacesome math does the replacements.



                            This would probably be better done with the l3regex package or really find and replace as many other people mentioned.



                            documentclassarticle
                            makeatletter
                            newtoksri@activechars
                            defaddreplacementrule#1#2addreplacementrule@#1@nil#2
                            defaddreplacementrule@#1#2@nil#3%
                            ri@activecharsexpandaftertheri@activechars\#1%
                            ri@maketransitions#2@nil#1#3%


                            defreplace#1%
                            begingroup
                            def\##1%
                            bgrouplccode`~=`##1lowercaseegroup
                            def~ri@continue##1%
                            %
                            catcode`##1=active
                            %
                            theri@activechars
                            scantokens#1%
                            endgroup


                            defri@maketransitions#1#2@nil#3#4%
                            deftemp#2%
                            ifxtempempty
                            expandafterdefcsname ri@lookup@detokenize#3#1endcsname#4%
                            letnextrelax
                            else
                            expandafterdefcsname ri@lookup@detokenize#3#1endcsnameri@continue#3#1%
                            defnextri@maketransitions#2@nil#3#1#4%
                            fi
                            next



                            defri@continue#1#2%
                            @ifundefinedri@lookup@detokenize#1#2%
                            detokenize#1#2%
                            %
                            csname ri@lookup@detokenize#1#2endcsname
                            %



                            begindocument
                            addreplacementrulex[2]x_2
                            addreplacementrulex[3]x^2

                            $x+1+x[2]+x[3]+x[1]$

                            replace$x+1+x[2]+x[3]+x[1]$
                            enddocument


                            enter image description here






                            share|improve this answer















                            Here's a solution. The command addreplacementruletext-to-replacereplacement-text specifies replacements to make. Then the command replacesome math does the replacements.



                            This would probably be better done with the l3regex package or really find and replace as many other people mentioned.



                            documentclassarticle
                            makeatletter
                            newtoksri@activechars
                            defaddreplacementrule#1#2addreplacementrule@#1@nil#2
                            defaddreplacementrule@#1#2@nil#3%
                            ri@activecharsexpandaftertheri@activechars\#1%
                            ri@maketransitions#2@nil#1#3%


                            defreplace#1%
                            begingroup
                            def\##1%
                            bgrouplccode`~=`##1lowercaseegroup
                            def~ri@continue##1%
                            %
                            catcode`##1=active
                            %
                            theri@activechars
                            scantokens#1%
                            endgroup


                            defri@maketransitions#1#2@nil#3#4%
                            deftemp#2%
                            ifxtempempty
                            expandafterdefcsname ri@lookup@detokenize#3#1endcsname#4%
                            letnextrelax
                            else
                            expandafterdefcsname ri@lookup@detokenize#3#1endcsnameri@continue#3#1%
                            defnextri@maketransitions#2@nil#3#1#4%
                            fi
                            next



                            defri@continue#1#2%
                            @ifundefinedri@lookup@detokenize#1#2%
                            detokenize#1#2%
                            %
                            csname ri@lookup@detokenize#1#2endcsname
                            %



                            begindocument
                            addreplacementrulex[2]x_2
                            addreplacementrulex[3]x^2

                            $x+1+x[2]+x[3]+x[1]$

                            replace$x+1+x[2]+x[3]+x[1]$
                            enddocument


                            enter image description here







                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited yesterday

























                            answered yesterday









                            Hood ChathamHood Chatham

                            4,3641428




                            4,3641428



























                                draft saved

                                draft discarded
















































                                Thanks for contributing an answer to TeX - LaTeX Stack Exchange!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid


                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.

                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function ()
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2ftex.stackexchange.com%2fquestions%2f481546%2fhow-can-i-replace-every-global-instance-of-x2-with-x-2%23new-answer', 'question_page');

                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                Popular posts from this blog

                                Triangular numbers and gcdProving sum of a set is $0 pmod n$ if $n$ is odd, or $fracn2 pmod n$ if $n$ is even?Is greatest common divisor of two numbers really their smallest linear combination?GCD, LCM RelationshipProve a set of nonnegative integers with greatest common divisor 1 and closed under addition has all but finite many nonnegative integers.all pairs of a and b in an equation containing gcdTriangular Numbers Modulo $k$ - Hit All Values?Understanding the Existence and Uniqueness of the GCDGCD and LCM with logical symbolsThe greatest common divisor of two positive integers less than 100 is equal to 3. Their least common multiple is twelve times one of the integers.Suppose that for all integers $x$, $x|a$ and $x|b$ if and only if $x|c$. Then $c = gcd(a,b)$Which is the gcd of 2 numbers which are multiplied and the result is 600000?

                                Србија Садржај Етимологија Географија Историја Политички систем и уставно-правно уређење Становништво Привреда Образовање Култура Спорт Државни празници Галерија Напомене Референце Литература Спољашње везе Мени за навигацију44°48′N 20°28′E / 44.800° СГШ; 20.467° ИГД / 44.800; 20.46744°48′N 20°28′E / 44.800° СГШ; 20.467° ИГД / 44.800; 20.467ууРезултати пописа 2011. према старости и полуу„Положај, рељеф и клима”„Europe: Serbia”„Основни подаци”„Gross domestic product based on purchasing-power-parity (PPP) valuation of country GDP”„Human Development Report 2018 – "Human Development Indices and Indicators 6”„Устав Републике Србије”Правопис српскога језикаGoogle DriveComparative Hungarian Cultural StudiesCalcium and Magnesium in Groundwater: Occurrence and Significance for Human Health„UNSD — Methodology”„Процене становништва | Републички завод за статистику Србије”The Age of Nepotism: Travel Journals and Observations from the Balkans During the Depression„The Serbian Revolution and the Serbian State”„Устав Србије”„Serbia a few steps away from concluding WTO accession negotiations”„A credible enlargement perspective for and enhanced EU engagement with the Western Balkans”„Freedom in the World 2017”„Serbia: On the Way to EU Accession”„Human Development Indices and Indicators: 2018 Statistical Update”„2018 Social Progress Index”„Global Peace Index”Sabres of Two Easts: An Untold History of Muslims in Eastern Europe, Their Friends and Foes„Пројекат Растко—Лузица”„Serbia: Introduction”„Serbia”оригинала„The World Factbook: Serbia”„The World Factbook: Kosovo”„Border Police Department”„Uredba o kontroli prelaska administrativne linije prema Autonomnoj pokrajini Kosovo i Metohija”оригиналаIvana Carevic, Velimir Jovanovic, STRATIGRAPHIC-STRUCTURAL CHARACTERISTICS OF MAČVA BASIN, UDC 911.2:551.7(497.11), pp. 1Archived„About the Carpathians – Carpathian Heritage Society”оригинала„O Srbiji”оригинала„Статистички годишњак Србије, 2009: Географски прегледГеографија за осми разред основне школе„Отворена, електронска база едукационих радова”„Влада Републике Србије: Положај, рељеф и клима”„Копрен (Стара планина)”„Туристичка дестинација-Србија”„Висина водопада”„РХМЗ — Републички Хидрометеоролошки завод Србије Кнеза Вишеслава 66 Београд”„Фауна Србије”„Српске шуме на издисају”„Lepih šest odsto Srbije”„Илустрована историја Срба — Увод”„Винчанска култура - Градска општина Гроцка”„''„Винча — Праисторијска метропола”''”оригиналаЈужни Словени под византијском влашћу (600—1025)Држава маћедонских Словена„Карађорђе истина и мит, Проф. др Радош Љушић, Вечерње новости, фељтон, 18 наставака, 24. август - 10. септембар 2003.”„Политика: Како је утврђена војна неутралност, 13. јануар. 2010, приступљено децембра 2012.”„Србија и РС оживеле Дејтонски споразум”„Са српским пасошем у 104 земље”Војска Србије | О Војсци | Војска Србије — Улога, намена и задациАрхивираноВојска Србије | ОрганизацијаАрхивираноОдлука о изради Стратегије просторног развоја Републике Србије до 2020. годинеЗакон о територијалној организацији Републике СрбијеЗакон о државној управиНајчешће постављана питања.„Смањење броја статистичких региона кроз измене Закона о регионалном развоју”„2011 Human development Report”„Službena upotreba jezika i pisama”„Попис становништва, домаћинстава и станова 2011. године у Републици Србији. Књига 4: Вероисповест, матерњи језик и национална припадност”„Вероисповест, матерњи језик и национална”„Специјална известитељка УН за слободу религије и вероисповести Асма Јахангир, код Заштитника грађана Саше Јанковића”„Закон о државним и другим празницима у Републици Србији”„Веронаука у српским школама”„Serbia – Ancestral Genography Atlas”Бела књига Милошевићеве владавинеоригиналаGross domestic product based on purchasing-power-parity (PPP) per capita GDP БДП 2007—2013Актуелни показатељи — Република Србија„Попис становништва, домаћинстава и станова 2011. године у Републици Србији Књига 7: Економска активност”Zemlje kandidati za članstvo u EU„Putin drops South Stream gas pipeline to EU, courts Turkey”„„Соко — историјат””оригинала„„Рембас — историјат””оригинала„„Лубница — историјат””оригинала„„Штаваљ — Историјат””оригинала„„Боговина — историјат””оригинала„„Јасеновац — историјат””оригинала„„Вршка чука — историјат””оригинала„„Ибарски рудници — историјат””оригинала„Закон о просторном плану Републике Србије од 2010 до 2020”„Кривични законик — Недозвољена изградња нуклеарних постројења, члан 267”„Б92: Srbija uklonila obogaćeni uranijum, 25. октобар 2011”„Коришћење енергије ветра у Србији — природни услови и практична примена”„Енергија ветра”„Србија може да прави струју од сунца, биомасе, воде и ветра”„Моја електрана и друге ветрењаче”„Биомаса, струја без инвестиција”„Auto-karte Srbije”„www.srbija.gov.rs Статистике о Србији”оригинала„Статистика зе месец децембар и 2016. годину”„Turizam u Srbiji”„Univerzitet u Beogradu: Vek i po akademskog znanja”„Vojnomedicinska akademija: 165 godina tradicije i napretka”Никола Гиљен, Соња Јовићевић Јов и Јелена Мандић: Мирослављево јеванђеље; Текст је публикован у ревији „Историја” и настао је као део научно-истраживачког рада Фонда „Принцеза Оливера”„World music асоцијација Србије”оригинала„World music у Србији”оригинала„Pogledajte: Boban Marković svira u redakciji „Blica”!”„Eurovision Song Contest 2007 Final”„Projekat Rastko, Alojz Ujes: Joakim Vujic”„Унеско”„Списак локалитета Светске баштине”„Guča i Egzit zaludeli svet”оригинала„Sabor trubača GUČA”„Interesting facts about Exit”оригинала„FIFA Association Information”„Serbia women win EuroBasket title, gain first Olympics berth”„Odbojkašice ispisale istoriju – Srbija je svetski prvak!”„Сајт Ватерполо савеза Србије, Освојене медаље”„Сајт ФК Црвена звезда, Бари”„Сајт ФК Црвена звезда, Токио”„Blic:Zlatna Milica! Mandićeva donela Srbiji najsjajnije odličje u Londonu!”„Милица Мандић освојила златну медаљу („Политика”, 12. август 2012)”„Златни Давор Штефанек”„DŽUDO ŠAMPIONAT Majdov osvojio svetsko zlato”„Španovićeva trećim skokom svih vremena do zlata!”„Чудо Иване Шпановић — 7,24 м („Политика”, 5. март 2017)”The Age of Nepotism: Travel Journals and Observations from the Balkans During the DepressionCalcium and Magnesium in Groundwater: Occurrence and Significance for Human HealthComparative Hungarian Cultural StudiesБела књига Милошевићеве владавинеоригиналаComparative Hungarian Cultural StudiesSabres of Two Easts: An Untold History of Muslims in Eastern Europe, Their Friends and FoesГеографија за осми разред основне школеSerbia: the country, people, life, customsМедијиВодичПодациВлада Републике СрбијеНародна скупштина Републике СрбијеНародна канцеларија председника Републике СрбијеНародна банка СрбијеТуристичка организација СрбијеПортал еУправе Републике СрбијеРепубличко јавно правобранилаштвоууууууWorldCat151202876n851959190000 0000 9526 67094054598-24101000570825ge130919

                                Barbados Ynhâld Skiednis | Geografy | Demografy | Navigaasjemenu