Lex:如何防止它与子字符串匹配?

发布于 2024-08-23 18:21:50 字数 136 浏览 7 评论 0原文

例如,我应该将“int”转换为“INT”。但如果有“integer”这个词,我认为它不应该变成“INTeger”。

如果我定义 "int" printf("INT"); 子字符串就会匹配。有没有办法防止这种情况发生?

For example, I'm supposed to convert "int" to "INT". But if there's the word "integer", I don't think it's supposed to turn into "INTeger".

If I define "int" printf("INT"); the substrings are matched though. Is there a way to prevent this from happening?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

情话墙 2024-08-30 18:21:51

好吧,这就是我的做法:

(("int"([a-z]|[A-Z]|[0-9])+)|(([a-z]|[A-Z]|[0-9])+"int")) ECHO;
"int" printf("INT");

欢迎更好的建议。

well, here's how i did it:

(("int"([a-z]|[A-Z]|[0-9])+)|(([a-z]|[A-Z]|[0-9])+"int")) ECHO;
"int" printf("INT");

better suggestions welcome.

下雨或天晴 2024-08-30 18:21:51

Lex 将为当前输入选择最长匹配的规则。为了避免子字符串匹配,您需要包含一个比 int 长的附加规则。最简单的方法是添加一个简单的规则,该规则拾取任何长于一个字符的字符串,即 [a-zA-Z]+。整个 lex 程序如下所示:-

%%

[\t ]+          /* skip whitespace */
int { printf("INT"); }
[a-zA-Z]+       /* catch-all to avoid substring matches */

%%

int main(int argc, char *argv[])
   {
   yylex();
   }

Lex will choose the rule with the longest possible match for the current input. To avoid substring matches you need to include an additional rule that is longer than int. The easiest way to do to this is to add a simple rule that picks up any string that is longer than one character, i.e. [a-zA-Z]+. The entire lex program would look like this:-

%%

[\t ]+          /* skip whitespace */
int { printf("INT"); }
[a-zA-Z]+       /* catch-all to avoid substring matches */

%%

int main(int argc, char *argv[])
   {
   yylex();
   }
爱你不解释 2024-08-30 18:21:50

我相信以下内容捕获了您想要的内容。

%{
#include <stdio.h>
%}

ws                      [\t\n ]

%%

{ws}int{ws}         { printf ("%cINT%c", *yytext, yytext[4]); }
.                       { printf ("%c", *yytext); }

要将其扩展到单词边界之外(在本例中为 {ws}),您需要向 ws 添加修饰符或添加更多特定检查。

I believe the following captures what you want.

%{
#include <stdio.h>
%}

ws                      [\t\n ]

%%

{ws}int{ws}         { printf ("%cINT%c", *yytext, yytext[4]); }
.                       { printf ("%c", *yytext); }

To expand this beyond word boundaries ({ws}, in this case) you will need to either add modifiers to ws or add more specifc checks.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文