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

PetitParser2解析器规则异常求助:含关键词文本未被拦截

问题原因

你的规则出现异常的核心原因在于keyword和word的定义逻辑冲突:

  1. 原andKeyword规则是'and' asPParser trim, #letter asPParser not,执行逻辑为:先匹配and并吃掉其前后所有空白,再检查当前位置字符不是字母。
  2. 当解析hello and bye时,前一个word的#blank star会吃掉hello后的空格,解析器定位到and的首字母a。此时尝试匹配keyword:
    • 'and' trim匹配and并吃掉其后空格,解析器跳到bye的首字母b;
    • 接下来#letter not检查b(是字母),匹配失败,导致整个keyword匹配失败;
    • 因此nonKeywordIdentifier中的keyword not条件通过,and被当成普通标识符匹配,最终words解析成功,不符合预期。

另外,原word规则将标识符后的空白纳入word的一部分,模糊了“单词”和“分隔符”的边界,也是次要诱因。

修正方案

重新调整规则逻辑,明确关键词的完整单词匹配,将空白作为单词分隔符而非单词的一部分:

"定义完整关键词:匹配and/not,且后面不是单词字符(确保是独立单词)"
andKeyword := 'and' asPParser, (#word asPParser not / endOfInput asPParser).
notKeyword := 'not' asPParser, (#word asPParser not / endOfInput asPParser).
"允许关键词前后带空白"
keyword := (andKeyword / notKeyword) trim.

"非关键词标识符:排除关键词,以字母开头,后跟任意单词字符"
nonKeywordIdentifier := keyword not, #letter asPParser, #word asPParser star.

"单个单词:仅匹配非关键词标识符,不包含空白"
word := nonKeywordIdentifier.

"多个单词:用一个或多个空白作为分隔符"
words := word separatedBy: #blank asPParser plus.
验证测试

修正后执行以下测试,结果符合预期:

words end parse: 'hello Pharo'. "解析成功" 
words end parse: 'hello and bye'. "解析失败,符合预期"
nonKeywordIdentifier end parse: 'hello'. "解析成功" 
nonKeywordIdentifier end parse: 'and'. "解析失败,符合预期"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 11:14:54