如何在Flex中编写以下正则表达式

How to write the following regex in Flex?

本文关键字:正则表达式 Flex      更新时间:2023-10-16

我正试图在flex中定义一个捕获"多行字符串"的规则
多行字符串是一个以三个撇号'''开头、以三个省略号结尾并且可以跨越多行的字符串
例如:

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

所以我的尝试是:

%{
#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;
}

适用于输入的:

'''This is
a multi
line
string!'''
This is
some random
text

输出为:

GotIt!
This is
some random
text

但对于该输入不起作用(或者,更准确地说,产生错误的输出):

'''This is
a multi
line
string!'''
This is
some random
text
'''and this
is another
multiline
string''' 

哪个生产:

GotIt!

这是因为我的规则说:
"扫描三个撇号,然后是任何可能的字符,然后是三个撇子",
相反,它应该说:
"扫描三个撇号,然后是任何可能的字符,除了三个撇子,然后是三个撇符"。

我该怎么做?

对于这样一个简单的否定,构造一个正则表达式相对容易:

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