【问题标题】:Regular expression in FLEX finding textFLEX 查找文本中的正则表达式
【发布时间】:2021-06-20 13:05:30
【问题描述】:

我得到了这个规则的 lex 文件:

%option noyywrap

%{
%}

LNA [^<>]
LNANA   [^<>!]

%%

(<!!)   fprintf(yyout, "begin_comment\t\t\t%s\n", yytext);
(!!>)   fprintf(yyout, "end_comment\t\t\t%s\n", yytext);
({LNANA}*|({LNA}{LNANA})*|{LNA}+{LNANA}{LNANA}{LNA})    fprintf(yyout, 
"string\t\t\t%s\n", yytext);
.   fprintf(yyout, "illegal char %s\n", yytext);
%%

我需要在“”和代码中的字符串什么都没有

例如

<!! This is a comment that need to be found !!>
simple string that need to be found also

这是我的输出:

如您所见,这不能按需要工作。 有什么帮助吗?

【问题讨论】:

  • 实际上,我看不出您的尝试“没有按需要工作”,因为您只提供了对您想要的内容的非常模糊的描述。请提供您期望的精确输出,作为文本(不是图像)。在编辑问题时,请将图像(在手机上难以阅读)替换为粘贴到问题中的实际文本。对于加分,请说明您认为您的每条规则的作用。

标签: c flex-lexer lex text-parsing


【解决方案1】:

我不确定你到底想要什么。

肯定有一个正则表达式可以匹配整个评论(只要您不打算让 cmets 嵌套)。但是很难做到正确,并且您通常最终会拆分字符串并返回不必要的令牌。这是一个我认为有效的方法,尽管它没有经过全面测试。由于您需要匹配整个注释,因此该模式必须包含注释分隔符。当然,你还必须匹配 cmets 之间的字符串,以及在注释没有正确终止的情况下做一些事情。

<!!([^!]*!)([^!]+!)*!+([^!>][^!]*!([^!]+!)*!+)*>   { /* Comment */ }
<!!    { /* This pattern will match on unterminated comments */ }
[^<]+  { /* Non comment text (but maybe not the whole string) */ }
<      { /* Also non-comment text */ }

一个可能更清晰也可能更慢的版本使用开始条件,并以单个片段的形式返回 cmets 的内部和其余文本(在 yytext 中,根据 yylex 接口)。

%x IN_COMMENT
%%
<!!                 { BEGIN(IN_COMMENT);
                      yytext[yyleng -= 3] = 0;
                      if (yyleng) return STRING;
                    }
    /* This patterns deliberately fails if it reaches the last input */
([^<]+|<)/(.|\n)    { yymore(); }
    /* The next pattern is to catch the last character in the input */
.|\n                { return STRING; }
<IN_COMMENT>!!>     { BEGIN(INITIAL);
                      yytext[yyleng -= 3] = 0;
                      return COMMENT;
                    }
<IN_COMMENT>[^!]+|! { yymore(); }
<IN_COMMENT><<EOF>> { fputs(stderr, "Unterminated comment\n"); }

【讨论】:

    猜你喜欢
    • 2011-07-24
    • 1970-01-01
    • 2017-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多