1

如何在 C++ 中使用 flex lexer 并修改令牌的yytext值?可以说,我有这样的规则:

"/*"    {
        char c;
        while(true)
            {
            c = yyinput();
            if(c == '\n')
                ++mylineno;

            if (c==EOF){
                yyerror( "EOF occured while processing comment" );
                break;
            }
            else if(c == '*')
                {
                if((c = yyinput()) == '/'){
                    return(tokens::COMMENT);}
                else
                    unput(c);
                }
            }
        }

我想在和tokens::COMMENT之间获得具有评论价值的令牌。(上述解决方案将“/*”作为值。/**/

另外,非常重要的是跟踪行号,所以我正在寻找支持它的解决方案。

编辑 当然我可以修改yytextyyleng值(如yytext+=1; yyleng-=1,但我仍然无法解决上述问题)

4

1 回答 1

1

我仍然认为开始条件是正确的答案。

%x C_COMMENT
char *str = NULL;
void addToString(char *data)
{
    if(!str)
    { 
        str = strdup(data);
    }
    else
    {
        /* handle string concatenation */
    }
}

"/*"                       { BEGIN(C_COMMENT); }
<C_COMMENT>([^*\n\r]|(\*+([^*/\n\r])))*    { addToString(yytext); }
<C_COMMENT>[\n\r]          { /* handle tracking, add to string if desired */ }
<C_COMMENT>"*/"            { BEGIN(INITIAL); }

我使用以下内容作为参考: http:
//ostermiller.org/findcomment.html
https://stackoverflow.com/a/2130124/1003855

您应该能够使用类似的正则表达式来处理字符串。

于 2013-04-05T14:58:22.607 回答