Search code examples
lex

Lexer rule (regex) for TeX equation


In TeX, equations are defined in between $...$. How can I define the lexer rule for lex, for the instance of any number of any characters between two dollar signs?

I tried:

equation  \$[^\$]*\$

without a success.


Solution

  • You can try using start conditions if you don't want the dollar signs to be included as part of the equation:

    %x EQN
    %%
    \$ { BEGIN(EQN); } /* switch to EQN start condition upon seeing $ */
    <EQN>{
        \$ { BEGIN(INITIAL); } /* return to initial state upon seeing another $ */
        [^\$]* { printf(yytext); } /* match everything that isn't a $ */
    }        
    

    Alternately instead of using BEGIN(STATE) you can use yy_push_state() and yy_pop_state() if you have other states defined in your lexer.