Lexer rule (regex) for TeX equation

2019-09-16 19:33发布

问题:

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.

回答1:

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.



标签: lex