Question

Can I pass a pattern as an argument when I run the file using lex something similar to grep. Iam trying to implement grep using lex.

%{
      #include <stdio.h>
      char *pattern;
%}
%%
.*{pattern}.*   printf("%s\n",yytext);
%%
int yywrap()
{
    return 1;
}
int main(int argc,char *argv[])
{
  if(argc<3)
  {
    printf("usage:lexgrep pattern filename\n");
    exit(0);
  }
  pattern=argv[1];
  yyin=fopen(argv[2],"r");
  yylex();
  return 0;
}

This is what I tried. But it didn't worked out. Any suggestions?

Was it helpful?

Solution

No, the pattern(s) that lex recognizes are specified at compile time, not run time. To interpret patterns at run time, you'll need to build your own state machine on the fly.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top