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:



  otherkeywords={^, \{, \}, ?, +},


  ((a+b){4,5})*c? + [^ab{?]{3}


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?
  • 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


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.

  • 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 .