Skip to main content

lex functions with examples

 Lex (Lexical Analyzer Generator) is a tool used to generate lexical analyzers (also known as tokenizers or scanners) for processing text input. Lex helps in breaking down input text into a sequence of tokens, which are then used by parsers and other components of a compiler or text processing system. Lex operates by defining regular expressions and associated actions to handle different patterns in the input text. Here are some commonly used Lex functions along with examples:


1. **Regular Expression Definitions:**

   

   Lex allows you to define regular expressions that match specific patterns in the input text. These regular expressions are used to identify tokens.


   ```lex

   %%

   [0-9]+    { printf("NUM: %s\n", yytext); }

   [a-zA-Z]+ { printf("ID: %s\n", yytext); }

   ```


   In this example, the regular expression `[0-9]+` matches sequences of digits (numbers), and `[a-zA-Z]+` matches sequences of letters (identifiers). When a match is found, the associated action (enclosed in curly braces) is executed.


2. **yytext:**

   

   `yytext` is a Lex variable that contains the current matched text from the input.


   ```lex

   %%

   "if"      { printf("Keyword: %s\n", yytext); }

   ```


   Here, when the input contains the keyword "if," `yytext` will contain the string "if."


3. **Regular Expression Anchors:**

   

   Anchors help to match patterns at the start or end of a line.


   ```lex

   %%

   ^BEGIN    { printf("Start of input\n"); }

   END$      { printf("End of input\n"); }

   ```


   In this example, `^BEGIN` matches if "BEGIN" appears at the beginning of a line, and `END$` matches if "END" appears at the end of a line.


4. **Regular Expression Ranges:**

   

   Ranges help to match characters within a specified range.


   ```lex

   %%

   [a-fA-F]  { printf("Hex character: %c\n", yytext[0]); }

   ```


   This matches any single character in the range `a` to `f` (case-insensitive).


5. **Start and End Conditions:**

   

   Lex allows you to define start conditions to handle different contexts in the input.


   ```lex

   %%

   <STRING>  { printf("String: %s\n", yytext); }

   

   \"        { BEGIN STRING; }

   \n        { /* Handle error or continue scanning */ }

   <STRING>\n { /* Handle error or continue scanning */ }

   ```


   In this example, when Lex encounters a double quote (`"`) it switches to the `STRING` start condition, and any text within the `STRING` condition is treated as a string until another double quote is encountered.


6. **Rule Patterns with Actions:**

   

   Lex rules consist of patterns and associated actions.


   ```lex

   %%

   "if"      { printf("Keyword: %s\n", yytext); }

   [0-9]+    { printf("Number: %s\n", yytext); }

   ```


   Lex processes the rules sequentially and executes the associated action for the first rule that matches.


7. **Contextual Matching:**

   

   Lex can use a trailing context to provide more context-aware tokenization.


   ```lex

   %%

   "if"      { printf("Conditional: %s\n", yytext); }

   "else"    { printf("Conditional: %s\n", yytext); }

   ```


   In this example, both "if" and "else" are recognized as conditionals.


8. **Ignoring Patterns:**

   

   Lex allows you to define patterns that are matched but ignored (not returned as tokens).


   ```lex

   %%

   "/*"      { BEGIN COMMENT; }

   <COMMENT>.|\n   ; /* Ignore characters in comments */

   <COMMENT>"*/"   { BEGIN INITIAL; }

   ```


   Here, when "/*" is encountered, Lex switches to the `COMMENT` start condition, ignoring characters until "*/" is found.


9. **Actions with Code:**

   

   You can include C code within Lex actions.


   ```lex

   %%

   [0-9]+    { int num = atoi(yytext); printf("Parsed Number: %d\n", num); }

   ```


   Here, the action converts the matched numeric string to an integer using `atoi()` and prints the parsed number.


These are just a few examples of Lex functions and features. Lex is a powerful tool for generating lexical analyzers, allowing you to define rules to tokenize and process input text according to specific patterns and requirements.

Comments

Popular posts from this blog

6. Generate a YACC specification to recognize a valid arithmetic expression that uses operators +, – , *,/ and parenthesis.

Below is a YACC specification for recognizing valid arithmetic expressions that involve operators (+, -, *, /) and parentheses. I'll explain each line of the code afterward: ```yacc %{ #include <stdio.h> %} %token NUMBER %left '+' '-' %left '*' '/' %% expression: expression '+' expression            | expression '-' expression            | expression '*' expression            | expression '/' expression            | '(' expression ')'            | NUMBER            ; %% int yylex() {     // Code for tokenizing input and returning tokens } void yyerror(const char *s) {     fprintf(stderr, "Error: %s\n", s); } int main() {     yyparse();     return 0; } ``` Now, let's break down the YACC specification line by line: 1. `%{` ... `%}`: This is the C code section where y...

ktu 2019 Cse Complier programing Lab Syllabus

 1Design and implement a lexical analyzer using C language to recognize all valid tokens  in the input program. The lexical analyzer should ignore redundant spaces, tabs and  newlines. It should also ignore comments. 2. Implement a Lexical Analyzer for a given program using Lex Tool. 3. Write a lex program to display the number of lines, words and characters in an input text. 4. Write a LEX Program to convert the substring abc to ABC from the given input string. 5. Write a lex program to find out the total number of vowels and consonants from the given  input string. 6. Generate a YACC specification to recognize a valid arithmetic expression that uses  operators +, – , *,/ and parenthesis. 7. Generate a YACC specification to recognize a valid identifier which starts with a letter  followed by any number of letters or digits.   8. Implementation of Calculator using LEX and YACC  9. Convert the BNF rules into YACC form and write code to generat...

1, Design and implement a lexical analyzer using C language to recognize all valid tokens in the input program. The lexical analyzer should ignore redundant spaces, tabs and newlines. It should also ignore comments

#include <stdio.h> #include <ctype.h> int main() {     char c;     while ((c = getchar()) != EOF) {         if (isspace(c)) {             // Ignore whitespace, tabs, and newlines             continue;         }         if (c == '/') {             // Check for comments             char nextChar = getchar();             if (nextChar == '/') {                 while ((nextChar = getchar()) != '\n');         ...