You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Arpeggio解析单行与多行注释?示例报错求助

Arpeggio正确处理单行与多行注释的方法

你按照Arpeggio官方示例定义了注释规则,但解析包含跨多行注释的文件时触发了arpeggio.NoMatch异常,核心问题出在多行注释的正则表达式上。

问题根源

官方示例中的多行注释正则/\*.*\*/存在两个缺陷:

  • .默认不匹配换行符,无法覆盖跨多行的/* */注释
  • 即使能匹配换行,贪婪匹配的.*会直接匹配到文件末尾,不会在第一个*/处停止

解决方案

修改多行注释的正则,使其能匹配所有字符(包括换行),并使用非贪婪匹配确保正确终止:

def comment():  return [_(r"//.*"), _(r"/\*[\s\S]*?\*/")]
  • [\s\S]等价于匹配任意字符(包括换行),替代默认不匹配换行的.
  • *?是非贪婪量词,会在找到第一个*/时停止匹配,避免过度贪婪

修改后的完整代码

from __future__ import unicode_literals

import os

from arpeggio import *
from arpeggio import RegExMatch as _


def comment():  return [_(r"//.*"), _(r"/\*[\s\S]*?\*/")]
def document(): return Kwd("hello"), _(r"[a-z]+"), '!', EOF


def main(filename, debug=False):
    current_dir = os.path.dirname(__file__)
    content = open(os.path.join(current_dir, filename), "r").read()
    parser = ParserPython(document, comment, debug=debug)
    parse_tree = parser.parse(content)


if __name__ == "__main__":
    main('simple.ex', debug=True)

验证效果

用你提供的待解析文件(包含跨多行注释和单行注释)测试,修改后的代码能正常完成解析,不会触发NoMatch异常。

内容的提问来源于stack exchange,提问作者Stefano Bragaglia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 11:47:12