Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
229 views
in Technique[技术] by (71.8m points)

c++ - How to write the following regex in Flex?

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    '''(.|
)*'''

%%

{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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...