How to write the following regex in Flex?

对着背影说爱祢 提交于 2019-12-13 10:16:38

问题


I'm trying to define a rule in flex that will capture a "multiline string".
A multiline string is a string that starts with three apostrophes: ''', ends with three apostrophes, and can span over multiple lines.
For example:

'''This is
an example of
a multiline
string'''

So my attempt at this was this:

%{
#include<iostream>
using std::cout;
using std::endl;

%}

MULTI_LN_STR    '''(.|\n)*'''

%%

{MULTI_LN_STR}  {cout<<"GotIt!";}   

%%

int main(int argc, char* argv[]) {

    yyin=fopen("test.txt", "r");

    if (!yyin) {
        cout<<"yyin is NULL"<<endl;
        return 1;
    }

    yylex();
    return 0;
}

Which works for the input:

'''This is
a multi
line
string!'''

This is
some random
text

The output is:

GotIt!

This is
some random
text

but does not work (or, to be more accurate, produces wrong output) for this input:

'''This is
a multi
line
string!'''

This is
some random
text

'''and this
is another
multiline
string''' 

Which produces:

GotIt!

This reason is because my rule says:
"scan for three apostrophes, followed by any possible character, followed by three apostrophes",
but rather, it should say:
"scan for three apostrophes, followed by any possible character except three apostrophes, followed by three apostrophes".

How can I do that?


回答1:


For a simple negation like this, it is relatively easy to construct a regular expression:

"'''"([^']|'[^']|''[^'])*"'''"


来源:https://stackoverflow.com/questions/26847704/how-to-write-the-following-regex-in-flex

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