描述正则表达式的上下文无关语法?

发布于 2024-07-23 05:18:57 字数 156 浏览 5 评论 0原文

我正在尝试编写一个正则表达式引擎。 我想手工编写一个递归下降解析器。 对于正则表达式语言(不是可以用正则表达式描述的语言)来说,没有左递归的上下文无关语法会是什么样子? 重构语法糖是否是最简单的,即将 a+ 更改为 aa* ? 提前致谢!

I'm trying to write a regular expression engine. I'd like to write a recursive descent parser by hand. What would a context-free grammar without left recursion for the language of regular expressions (not the languages that can be described by regular expressions) look like? Would it be easiest to re-factor out the syntactic sugar, i.e. change a+ to aa* ? Thanks in advance!

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

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

发布评论

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

评论(3

樱花细雨 2024-07-30 05:18:57

左递归:

Expression = Expression '|' Sequence
           | Sequence
           ;

Sequence = Sequence Repetition
         | <empty>
         ;

右递归:

Expression = Sequence '|' Expression
           | Sequence
           ;

Sequence = Repetition Sequence
         | <empty>
         ;

不明确形式:

Expression = Expression '|' Expression
           | Sequence
           ;

Sequence = Sequence Sequence
         | Repetition
         | <empty>
         ;

Left recursion:

Expression = Expression '|' Sequence
           | Sequence
           ;

Sequence = Sequence Repetition
         | <empty>
         ;

Right recursion:

Expression = Sequence '|' Expression
           | Sequence
           ;

Sequence = Repetition Sequence
         | <empty>
         ;

Ambiguous form:

Expression = Expression '|' Expression
           | Sequence
           ;

Sequence = Sequence Sequence
         | Repetition
         | <empty>
         ;
半窗疏影 2024-07-30 05:18:57

您可以查看Plan 9 grep 的源代码。 文件 grep.y 有一个用于正则表达式的 yacc (LALR(1),如果我没记错的话)语法。 您也许可以从 yacc 语法开始,并重写它以进行递归下降解析。

You could look at the source code for Plan 9 grep. The file grep.y has a yacc (LALR(1) if I recall correctly) grammar for regular expressions. You might be able to start from the yacc grammar, and rewrite it for recursive descent parsing.

仅此而已 2024-07-30 05:18:57

关于左递归的维基百科文章提供了关于如何实现这一点的很好的信息。

The wikipedia article on Left Recursion gives pretty good info on how to pull this off.

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