8

A coworker is currently writing a long document with a focus on regular expressions. We would like to be able to format the regular expressions as a listings language, with syntax highlighting and such.

The main difficulty arises from the fact that the elements to highlight in the code are "special" characters such as ? + { } ( ) ^ [ ].

I have tried the following definition:

\documentclass[12pt]{article}

\usepackage{listings}

\lstdefinelanguage{regex}{
  commentstyle=\color{gray},
  keywords={},
  otherkeywords={^, \{, \}, ?, +},
  alsoletter={},
  basicstyle=\ttfamily,
  keywordstyle=\bfseries\color{green},
  breakatwhitespace=false,
  breaklines=true,
  captionpos=b,
  showspaces=false,
  showstringspaces=true,
  literate=%
  *{0}{{{\color{red}0}}}1
  {1}{{{\color{red}1}}}1
  {2}{{{\color{red}2}}}1
  {3}{{{\color{red}3}}}1
  {4}{{{\color{red}4}}}1
  {5}{{{\color{red}5}}}1
  {6}{{{\color{red}6}}}1
  {7}{{{\color{red}7}}}1
  {8}{{{\color{red}8}}}1
  {9}{{{\color{red}9}}}1
  {(}{{{\bfseries\color{blue}(}}}1
  {)}{{{\bfseries\color{blue}\)}}}1
}

\begin{document}

\begin{lstlisting}[language=regex]
  ((a+b){4,5})*c? + [^ab{?]{3}
\end{lstlisting}

\end{document}

Which seems a bit hacky but close to working. I have two main questions:

  1. only the opening round brackets are coloured, not the closing ones, how could I fix this? I have tried setting the brackets as keywords, no success there.
  2. would it be possible to make this definition more $\LaTeX$ standard compliant/optimised?
2
  • You have \) should be ) like ( on the line above Commented Jul 3, 2023 at 18:42
  • Hi David, thanks for the comment. This solution does not work for me either. The bracket is shown, but not in colour.
    – olirwin
    Commented Jul 4, 2023 at 8:08

1 Answer 1

7

Since I could not find an answer to this issue using listings, I decided to give it a go with minted, by creating a custom lexer for regular expressions, which seems to be the best possible solution.

The lexer is not currently available on PyPi, and is not yet perfect (but all suggestions are welcome). You can clone the repo from here. The installation can be done with a classic pip install . and then the lexer is available in both minted and Pygments.

2
  • 4
    Would you mind to share the lexer?
    – egreg
    Commented Jul 5, 2023 at 15:42
  • @egreg, done! If at any point you have suggestions for improvements, please send them through
    – olirwin
    Commented Jul 6, 2023 at 8:12

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .