📜  Lex程序可识别有效的算术表达式并识别标识符和运算符

📅  最后修改于: 2021-06-28 07:44:42             🧑  作者: Mango

问题:编写Lex程序以识别有效的算术表达式并识别标识符和运算符。

解释:
Flex(快速词法分析器生成器)是由Vern Paxson在1987年左右用C编写的用于生成词法分析器(扫描器或词法分析器)的工具/计算机程序。Lex读取指定词法分析器的输入流,并输出在C语言中实现词法分析器的源代码编程语言。函数yylex()是运行规则部分的主要flex函数。

例子:

Input: a+b*c
Output: valid expression
        the operators are :
        + 
        * 
        the identifiers  are :
        a 
        b 
        c

Input: a+b-
Output: invalid expression
 
Input: (a*b)
Output: valid expression
        the operators are :
        * 
        the identifiers are :
        a 
        b 

Input: (a+b-
Output: invalid expression 

执行:

/* Lex program to recognize valid arithmetic expression
        and identify the identifiers and operators */
%{ 
#include  
#include  
    int operators_count = 0, operands_count = 0, valid = 1, top = -1, l = 0, j = 0; 
    char operands[10][10], operators[10][10], stack[100]; 
%} 
%%
"(" { 
    top++; 
    stack[top] = '('; 
} 
"{" {
    top++; 
    stack[top] = '{'; 
} 
"[" { 
    top++; 
    stack[top] = '['; 
} 
")" { 
    if (stack[top] != '(') { 
        valid = 0;     
    } 
    else if(operands_count>0 && (operands_count-operators_count)!=1){
        valid=0;
    }
    else{
        top--;
        operands_count=1;
        operators_count=0;
    } 
} 
"}" { 
    if (stack[top] != '{') { 
        valid = 0;     
    } 
    else if(operands_count>0 && (operands_count-operators_count)!=1){
        valid=0;
    }
    else{
        top--;
        operands_count=1;
        operators_count=0;
    } 
} 
"]" { 
    if (stack[top] != '[') { 
        valid = 0; 
    } 
    else if(operands_count>0 && (operands_count-operators_count)!=1){
        valid=0;
    }
    else{
        top--;
        operands_count=1;
        operators_count=0;
    } 
          
} 
"+"|"-"|"*"|"/" { 
    operators_count++; 
    strcpy(operators[l], yytext); 
    l++; 
} 
[0-9]+|[a-zA-Z][a-zA-Z0-9_]* { 
    operands_count++; 
    strcpy(operands[j], yytext); 
    j++; 
} 
%% 
  
  
int yywrap() 
{ 
    return 1; 
} 
int main() 
{ 
    int k; 
    printf("Enter the arithmetic expression: "); 
    yylex(); 
  
    if (valid == 1 && top == -1) { 
        printf("\nValid Expression\n"); 
    } 
    else
        printf("\nInvalid Expression\n"); 
  
    return 0;
} 

输出: