Im really new to flex and sadly there are very few examples on the internet compared to other languages. I want to replace the words:
I did some research and the only thing i find is replace just 1 word with another word in a string. which is totally different.
Just some progress i made:
TODAY "TODAY"
YESTERDAY "YESTERDAY"
TOMORROW "TOMORROW"
TODAY+n "TODAY+n"
TODAY-n "TODAY-n"
%%
{TODAY} {op=1;}
{YESTERDAY} {op=2;}
{TOMORROW} {op=3;}
{TODAY+n} {op=4;}
{TODAY-n} {op=5;}
%%
date()
{
if (op==0)
a=(yytext);
switch(op)
{
case 1:TODAY;
break;
case 2:YESTERDAY;
break;
case 3:TOMORROW;
break;
case 4;TODAY+n;
break;
case 5;TODAY-n;
break;
}
op=0;
}
Here's a very basic implementation, concentrating on flex rather than the intricacies of computing and showing dates. It depends on the fact that the default action for unrecognised characters is to copy them to the output stream. However, to avoid recognising TODAY
in the middle of a word (like AATODAYBB
), I added a pattern which matches any word consisting only of alphabetic characters and copies it to the output stream explicitly (using ECHO
). Depending on your actual needs, you might want to adjust that.
A quick read of the flex manual should be sufficient to understand the program. In particular, take a look at the introductory material, including simple examples; the description of patterns (which is similar but not identical to standard regular expressions, but missing a lot of costly features like captures); and the description of the way the input is scanned. That last section also explains the so-called "maximal munch" (first longest match) algorithm which is used here in the last rule (which must be the last rule).
%option noinput nounput noyywrap
%{
#include <stdio.h>
#include <string.h>
/* Replace this with a function which actually shows the correct date */
void show_date(int offset) {
if (offset > 0)
fprintf(yyout, "<today's date + %d>", offset);
else
fprintf(yyout, "<today's date %.0d>", offset);
}
%}
%%
TODAY { show_date(0); }
TOMORROW { show_date(1); }
YESTERDAY { show_date(-1); }
TODAY[+-][0-9]+ { show_date(atoi(yytext + 5)); /* +5 to skip TODAY */ }
[[:alpha:]]+ { ECHO; /* Avoid false matches. See text. */ }
To compile and run:
# (Assuming the above file is called date_subst.l)
flex -o date_subst.c date_subst.l
gcc -Wall -g -o date_subst date_subst.c -lfl
./date_subst