如何创建正则表达式解析带有主体的类似 pascal 的函数声明?

发布于 2024-10-17 06:00:18 字数 288 浏览 7 评论 0原文

如何创建(这是否可能)使用 body 解析类似 pascal 的函数声明的正则表达式? 我创建了一些正则表达式

 function\s+(\w+)(\(((((var\s*)?(\w+)(\s*\,+\s*)?)+?\s*\:\s*(\w+)\s*\;?\s*?)\s*)+\))?\s*\:\s*(\w+)

,它只能池化函数原型(它仅在没有注释的情况下才有效,所以我在解析之前清除注释),并且我不知道如何更改它以使其与主体池化函数。问题是可能有很多“开始 - 结束”块,因此很难找到结束的函数

How to create (and is this possible) regexp parsing pascal-like function declaration with body ?
I've created some regexp

 function\s+(\w+)(\(((((var\s*)?(\w+)(\s*\,+\s*)?)+?\s*\:\s*(\w+)\s*\;?\s*?)\s*)+\))?\s*\:\s*(\w+)

which can pool only functions prototypes (it works only if there is no comments, so i clear comments before parsing ) and i have no idea how to change it to make it pool functions with bodies. The problem is there are can be many of "begin - end" blocks, so it is hard to find functions ending

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

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

发布评论

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

评论(1

梦魇绽荼蘼 2024-10-24 06:00:19

抱歉,您使用了错误的工具。编程语言具有上下文无关的结构,正则表达式根本无法可靠地识别。正确嵌套的括号如 { () [] } { } 是此类上下文无关结构的一个示例,您无法找到用于检查正确嵌套的正则表达式。

为了解决这个问题,您可以使用正则表达式将程序代码分解为令牌流,然后使用(手动编码的)自顶向下解析器检查该令牌流的结构。要了解这一点,请查阅任何有关编译器设计的书籍。扫描(分解标记)和解析(检查结构)始终是第一章。 自顶向下解析器的维基百科条目提供了一个示例。

Sorry, but you are using the wrong tool. Programming languages have a context-free structure that regular expressions simply cannot recognize reliably. Properly nested parentheses like { () [] } { } are an example for such a context-free structure for which you cannot find a regular expression that checks the proper nesting.

To solve the problem, you could use regular expression to break down program code into a stream of tokens and then use a (manually coded) top-down parser to check the structure of this token stream. To learn about this, consult any book about compiler design. Scanning (breaking into tokens) and parsing (checking structure) are always the first chapters. The Wikipedia entry for a top-down parser provides an example.

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