需要 Lex 正则表达式来匹配字符串到换行符

Need Lex regular expression to match string upto newline

我想解析类型的字符串:

a=some value
b=some other value

“=”周围没有空格,并且值会扩展到换行符。可能有前导空格。

我的 lex 规范(相关部分)是:

%%  
a=  { printf("Found attr %s\n", yytext); return aATTR; }
^[ \r\t]+   { printf("Found space at the start %s\n", yytext); }
([^a-z]=).*$  { printf("Found value %s\n", yytext); }
\n  { return NEWLINE; }
%%  

我尝试了 .*$ [^\n]* 和其他一些正则表达式,但无济于事。 这看起来很简单。有什么建议么?我也知道 lex returns 是最长的匹配,因此使它进一步复杂化。我得到整行匹配我尝试过的一些正则表达式。

您可能想要合并单独的开始状态。这些允许您对简单的上下文进行编码。下面的简单示例在每次调用 yylex() 时捕获您的 ID、运算符和值。

%{
char id;
char op;
char *value;
%}

%x VAL OP
%%
<INITIAL>[a-z]+ {
    id = yytext[0];
    yyleng = 0;
    BEGIN OP;
}
<INITIAL,OP>[ \t]*
<OP>=[ \t]* {
    op = yytext[0];
    yyleng = 0;
    BEGIN VAL;
}
<VAL>.*\n {
    value = yytext;
    BEGIN INITIAL;
    return 1;
}
%%