Lex program to identify the identifier

Lex is a computer program that generates lexical analyzers and was written by Mike Lesk and Eric Schmidt. Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lex in the C programming language.

In C, an identifier must begin with either an alphabet or underscore, it can not begin with a digit or any other special character, moreover digits can come after.

Example:



gfg : valid identifier
123 : invalid identifier
_abc12 : valid identifier
#abc : invalid identifier

Let’s see the lex program to determine whether input is an identifier or not.

filter_none

edit
close

play_arrow

link
brightness_4
code

/*lex code to determine whether input is an identifier or not*/
% {
#include <stdio.h>
    %
}
  
    / rule section % %
    // regex for valid identifiers
    ^[a - z A - Z _][a - z A - Z 0 - 9 _] * printf("Valid Identifier");
  
// regex for invalid identifiers
^[^a - z A - Z _] printf("Invalid Identifier");
.;
% %
  
    main()
{
    yylex();
}

chevron_right


Output:



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.