Skip to content
Related Articles

Related Articles

Improve Article

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

  • Last Updated : 12 Mar, 2021

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 

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:


/* lex code to check for characters other that 
albhabets 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(){
    return 0;


Attention reader! Don’t stop learning now. Get hold of all the important CS Theory concepts for SDE interviews with the CS Theory Course at a student-friendly price and become industry ready.


My Personal Notes arrow_drop_up
Recommended Articles
Page :