用flex进行改写
时间: 2023-06-30 17:06:25 浏览: 44
以下是一个简单的例子,使用 Flex 将输入的数字转换为英文单词:
```
%{
#include <stdio.h>
%}
DIGIT [0-9]
%%
{DIGIT}+ {
int num = atoi(yytext);
switch (num) {
case 1:
printf("one ");
break;
case 2:
printf("two ");
break;
case 3:
printf("three ");
break;
case 4:
printf("four ");
break;
case 5:
printf("five ");
break;
case 6:
printf("six ");
break;
case 7:
printf("seven ");
break;
case 8:
printf("eight ");
break;
case 9:
printf("nine ");
break;
default:
printf("invalid input ");
break;
}
}
\n {
printf("\n");
}
. {
printf("invalid input ");
}
%%
int main() {
yylex();
return 0;
}
```
在上面的代码中,我们首先定义了一个名为 `DIGIT` 的宏,表示数字。接着,在正则表达式中使用了这个宏来匹配输入中所有的数字。
当匹配到数字时,我们将其转换为整数并进行判断,根据不同的数字输出不同的英文单词。如果输入的不是数字,则输出 "invalid input"。
`\n` 表示换行符,当输入中出现换行符时,输出一个换行符。
`.` 匹配所有未被其他规则匹配到的字符,也就是输入中不是数字也不是换行符的字符,输出 "invalid input"。
在 `main()` 函数中,我们调用了 `yylex()` 函数来启动 Flex,开始对输入进行词法分析。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)