Skip to content
Related Articles

Related Articles

Lex Program to Find if a Character Apart from Alphabet Occurs in a String

View Discussion
Improve Article
Save Article
  • Last Updated : 10 Oct, 2021
View Discussion
Improve Article
Save Article

Lex is a computer program that generates lexical analyzers. Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in the C programming language.

The commands for executing the lex program are:

lex abc.l (abc is the file name)
cc lex.yy.c 
./a.out

Problem: Write a lex program to find if a character apart from the alphabet occurs in a given string.

Example :

Input : GeeksforGeeks is best
Output : other characters are also present
Explanation: Because ' ' space is also a character

Input : geeksforgeeks
Output : only alphabets present
Explanation: Only english alphabets are present in the string

Approach :

  1. Using the flag to check if other characters are also present or not;
  2. If “\n” is encountered we will assume that the user has given the string completely and now he wants the result to be displayed
  3. So according to the state of flag, we will show the output.
  4. Else if any other character except (a-z, A-Z) is encountered we will make the flag = 1 which we are checking via Regular expression.

Below is the implementation:

C++




/* lex code to check for characters other that
alphabets in a given string */
 
%{
int flag = 0;
%}
 
%%
[\n] {
    flag==0?printf("Only alphabets present\n"):
    printf("Other characters are also present\n");
    flag = 0;
}
 
[^a-zA-Z] {flag = 1;}
 
. {}
%%
 
int yywrap(void) {}
 
int main(){
    yylex();
    return 0;
}

Output:

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!