FLEX:有没有办法一次返回多个令牌

发布于 2024-07-14 04:22:07 字数 49 浏览 3 评论 0原文

在 Flex 中,我想为正则表达式的一次匹配返回多个标记。 有没有办法做到这一点?

In flex, I want to return multiple tokens for one match of a regular expression. Is there a way to do this?

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

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

发布评论

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

评论(3

愛放△進行李 2024-07-21 04:22:07

我这样做的方法是创建一个要返回的令牌队列,并在 yylex() 的开头检查令牌并返回它们。

The way I've been doing this is to create a queue of to-be-returned tokens, and at the beginning of yylex(), check for tokens and return them.

对你而言 2024-07-21 04:22:07

您是指所有匹配项吗? 您使用的是正则表达式函数还是字符串函数? 使用全局标志。

至于flex,我认为你无法做到这一点。 您一次测试与一种模式的匹配,因此这可能超出了范围。 你为什么想要那个? 作为优化? 范围界定问题?

Do you mean all matches? Are you using regex functions or string functions? Use the global flag.

As for flex, I don't think you can do that. You test for a match with one pattern at a time so that's probably out of scope. Why'd you want that? As an optimization? Scoping issues?

遮了一弯 2024-07-21 04:22:07

通常,这是由扫描器顶部的解析器处理的,它可以为您提供更清晰的代码。 您可以在某种程度上用状态来模拟这一点:

%option noyywrap

%top {
#define TOKEN_LEFT_PAREN    4711
#define TOKEN_RIGHT_PAREN   4712
#define TOKEN_NUMBER        4713
}

%x PAREN_STATE
%%
"("         BEGIN(PAREN_STATE); return TOKEN_LEFT_PAREN;
<PAREN_STATE>{
   [0-9]+   return TOKEN_NUMBER;
   ")"      BEGIN(INITIAL); return TOKEN_RIGHT_PAREN;
   .|\n     /* maybe signal syntax error here */
}
%%
int main (int argc, char *argv [])
{
  int i;

  while ((i = yylex ()))
    printf ("%d\n", i);

  return 0;
}

但是一旦您的语法变得更加复杂,这就会变得非常混乱。

Usually, this is handled by a parser on top of the scanner which gives you much cleaner code. You can emulate that to some degree with states:

%option noyywrap

%top {
#define TOKEN_LEFT_PAREN    4711
#define TOKEN_RIGHT_PAREN   4712
#define TOKEN_NUMBER        4713
}

%x PAREN_STATE
%%
"("         BEGIN(PAREN_STATE); return TOKEN_LEFT_PAREN;
<PAREN_STATE>{
   [0-9]+   return TOKEN_NUMBER;
   ")"      BEGIN(INITIAL); return TOKEN_RIGHT_PAREN;
   .|\n     /* maybe signal syntax error here */
}
%%
int main (int argc, char *argv [])
{
  int i;

  while ((i = yylex ()))
    printf ("%d\n", i);

  return 0;
}

but this will get very messy as soon as your grammar gets more complex.

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