consider using TexSoup for parsing

Author: ivanistheoneCreated Feb 4, 2025Updated Feb 4, 2025

It's very impressive how far you can get with regexes, but wanted to flag there is a Python parser for .tex/.latex you can check out here: https://github.com/alvinwan/TexSoup

It used to choke on some syntax elements, but works for 95% + of what you might find.

Very clean API reminiscent of BeautifulSoup parsers for HTML.

Source: google-research/arxiv-latex-cleaner