I need to use subscript and superscript in a lstlisting block. lstlisting can replace strings by Latex commands, but is it also possible to replace some kind of regular expression like

_<something> and ^<something>

to identify the strings, that shall be replaced?

Thanks :-)


Probably the simplest way to do this is to use the option mathescape in a \lstset command. This will not only allow you to use superscripts and subscripts, but will also give you access to other things you can do in mathmode. It may also do subtle and strange things to your formatting, but you can perhaps account for this where it matters to you.




R -> ε | $\ell$ | (R|R) | (RR) | R$^\ast$
$\ell\,$ ->  a | b | c | $\cdots$


Example of using mathescape in a lstlisting

  • 2
    Perhaps it might be better to actually show subscripts and superscripts in your example, which is what the OP is asking for explicitly. – Michael Jun 14 '14 at 13:37
  • I may elaborate the example with subscripts and (more) superscripts later today. The R$^\ast$ is a superscript. – Niel de Beaudrap Jun 14 '14 at 13:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.