问题
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