Category Archives: Lex

Lex : Check Valid Email

%{
#include<stdio.h>
#include<stdlib.h>
int flag=0;
%}
%%
[a-z . 0-9]+@[a-z]+".com"|".in" { flag=1; }
%%
int main()
{
yylex();
if(flag==1)
printf("Accepted");
else
printf("Not Accepted");
}

/*
Enter input
press Enter & ctrl+d to get output
*/

Output :-
abc@gmail.com
Accepted

Lex : Number is prime or not

%{
#include<stdio.h>
#include<stdlib.h>
int flag,c,j;
%}
%%
[0-9]+ {c=atoi(yytext);}
%%
int main()
{
yylex();
if(c==2)
{
printf("\n Prime number");
}
else if(c==0 || c==1)
{
printf("\n Not a prime number");
}
else
{
for(j=2;j<c;j++)
{
if(c%j==0)
flag=1;
}
if(flag==1)
printf("\n Not a prime number");
else if(flag==0)
printf("\n Prime number");
}
}

Lex : Check Whether number is Even or Odd

%{
#include<stdio.h>
#include<stdlib.h>
int i;
%}
%%
[0-9]+ {i=atoi(yytext); if(i%2==0) printf("Even !"); else printf("Odd !");};
%%
int main()
{
yylex();
}
/*  To Compile :-
1) lex filename.l
2) gcc lex.yy.c -ll
3) ./a.out
Enter Input and press enter
*/

Output :-
145
Odd !
204
Even !

LEX : Count Vowels & Consonants in a String

%{
#include<stdio.h>
int vcount=0,ccount=0;
%}
%%
[a|i|e|o|u|E|A|I|O|U] {vcount++;}
[a-z A-Z (^a|i|e|o|u|E|A|I|O|U) ] {ccount++;}
%%
int main()
{
yylex();
printf("No. of Vowels :%d\n",vcount);
printf("No. of Consonants :%d\n",ccount);
return 0;
}

/* To Compile :
1) lex FileName.l
2) gcc lex.yy.c -ll
3) ./a.out
Type String and then press ctrl+D to get the result.
*/

Output :-

hello
No. of Vowels :2
No. of Consonants :3