[Tex/LaTex] How to replace every global instance of “x[2]” with “x_2”

macrosshorthands

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 \newcommand{\ga}{\gamma} 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

\newcommand{x[2]}{x_2}

and

\newcommand{a[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)

Best Answer

An extensible set of replacements:

\documentclass{article}
\usepackage{amsmath}
\usepackage{xparse}

\ExplSyntaxOn
\NewDocumentCommand{\trans}{m}
 {
  \tl_set:Nn \l__brad_trans_tl { #1 }
  \regex_replace_all:nnN { \[(.*?)\] } { \c{sb}\cB\{\1\cE\} } \l__brad_trans_tl
  \regex_replace_all:nnN { a } { \c{alpha} } \l__brad_trans_tl
  % other replacements
  % ...
  % deliver the new token list
  \l__brad_trans_tl
 }
\ExplSyntaxOff

\begin{document}

$\trans{x[1]+x[2]^2+a+a[3]}$

\end{document}

enter image description here

Related Question