微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在 lex 中编写一个否定空格的正则表达式

如何解决如何在 lex 中编写一个否定空格的正则表达式

我是 Lex (Flex) 的新手,我正在解决一个问题,该问题要求我编写一个复制文件的 lex 程序,用一个空格替换每个非空的空格序列。 这是我尝试过的

%{
    FILE *rp,*wp;
    /*Read pointer and write pointer*/
%}

delim   [ \t\n]
ws      {delim}+
Nows    [^{ws}]
%%
{Nows}  {fprintf(wp,"%s",yytext);}
{ws}    {fprintf(wp,"%c",' ');}
%%
int yywrap(){}

int  main(int argc,char** argv){
    rp=fopen(argv[1],"r");
    wp=fopen(argv[2],"w+");
    yyin=rp;
    yylex();
    fclose(yyin);
    fclose(wp);
    return 0;
}

我认为使用插入符号 (^) 字符我会匹配除空格以外的任何字符,但相反,它从输入中删除ws
那么有谁知道我怎样才能否定空格?另外,欢迎使用任何其他方法解决问题。
提前致谢。

解决方法

借助 Alfred V Aho 和 Jeffrey D Ullman 关于编译器的书的帮助,这里有一个解决上述问题的方法。 ws 可以定义为 ws [\t \n]+,nows 可以定义为 nows .。 尽管 . 用于匹配所有字符,但由于 ws 将首先写入,因此,lex 在看到空格字符时将匹配此规则。 因此完整的代码变成了

%{
    #include<stdio.h>
    FILE *rp,*wp;
    /*Read pointer and write pointer*/
%}

ws      [\t \n]+
nows    .
%%
{nows}  {fprintf(wp,"%s",yytext);}
{ws}    {fprintf(wp," ");}
%%
int yywrap(){}

int  main(int argc,char** argv){
    rp=fopen(argv[1],"r");
    wp=fopen(argv[2],"w");
    yyin=rp;
    yylex();
    fclose(yyin);
    fclose(wp);
    return 0;
}

这是一个演示程序工作的输入和输出文件
输入.txt

This is     a test  file   for 
the 
    program copy.l This file must be properly
formatted.
Here   we are trying to
    
        write     some gibberish   
    Also here is   some line.

这是它的输出
输出.txt

This is a test file for the program copy.l This file must be properly formatted. Here we are trying to write some gibberish Also here is some line.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。