Regex matching string

孤街醉人 提交于 2019-12-24 19:33:44

问题


I am implementing a compiler and one thing I'd like to do is the string concatenation using '+', eg:

str_cnct = "hi" + "dear"

So the value now is "hidear".

The problem is that my regex in flex captures all of it directly as a string giving "hi + dear". My current regex is: \".*\"

{string}                {
                            yylval.struct_val.val.chain = (char *)malloc(sizeof(char)*yyleng);
                            strncpy(yylval.struct_val.val.chain,yytext,yyleng);
                            remove_char(yylval.struct_val.val.chain);
                            yylval.struct_val.length = yyleng;
                            yylval.struct_val.line = yylineno;
                            yylval.struct_val.column = columnno + yyleng + 2;
                            printf("--- String: %s\n", yylval.struct_val.val.chain);
                            return(STRING);
                    }

How to avoid this and capture "hi" then '+' as operator and then "dear"?

Thanks in advance


回答1:


Try something like the following:

^\"([^\"]*)\"\s*\+\s*\"([^\"]*)\"$

$1 will capture "hi" w/o quotes and $2 will capture "dear" w/o quotes for string '"hi" + "dear"'.




回答2:


I finally went through it like this:

%x MATCH_STR
quotes \"
%%

{quotes}                { BEGIN(MATCH_STR); }

<MATCH_STR>[\n]         { yyerror("String not closed"); }

<MATCH_STR>[^"^\n]*     {
                        yylval.struct_val.val.chain = (char *)malloc(sizeof(char)*yyleng);
                        strncpy(yylval.struct_val.val.chain,yytext,yyleng);
                        remove_char(yylval.struct_val.val.chain);
                        yylval.struct_val.length = yyleng;
                        yylval.struct_val.line = yylineno;
                        yylval.struct_val.column = columnno + yyleng + 2;
                        printf("--- String: %s\n", yylval.struct_val.val.chain);
                        return(STRING);
                        }

<MATCH_STR>{quotes}     { BEGIN(INITIAL); }


来源:https://stackoverflow.com/questions/21025157/regex-matching-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!