强制和可选空格
我需要解析这样的字符串:
"qqq www eee" -> "qqq", "www", "eee" (case A)
"qqq www eee" -> "qqq", "www", "eee" (case B)
这是我当前拥有的语法:
grammar Query;
SHORT_NAME : ('a'..'z')+ ;
name returns [String s]: SHORT_NAME { $s = $SHORT_NAME.text; };
names
returns [List<String> v]
@init { $v = new ArrayList<String>(); }
: name1 = name { $v.add($name1.s); }
(' ' name2 = name { $v.add($name2.s); })*;
它对于 caseA
工作正常,但对于 caseB
失败:
line 1:4 missing SHORT_NAME at ' '
line 1:5 extraneous input ' ' expecting SHORT_NAME
line 1:10 extraneous input ' ' expecting SHORT_NAME
有什么想法如何让它工作吗?
I need to parse strings like this:
"qqq www eee" -> "qqq", "www", "eee" (case A)
"qqq www eee" -> "qqq", "www", "eee" (case B)
Here's the grammar I currently have:
grammar Query;
SHORT_NAME : ('a'..'z')+ ;
name returns [String s]: SHORT_NAME { $s = $SHORT_NAME.text; };
names
returns [List<String> v]
@init { $v = new ArrayList<String>(); }
: name1 = name { $v.add($name1.s); }
(' ' name2 = name { $v.add($name2.s); })*;
It works fine for caseA
, but fails for caseB
:
line 1:4 missing SHORT_NAME at ' '
line 1:5 extraneous input ' ' expecting SHORT_NAME
line 1:10 extraneous input ' ' expecting SHORT_NAME
Any ideas how to make it work?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
从
names
规则中删除文字' '
并将其替换为SPACES
标记:或者简单地丢弃词法分析器级别的空格,以便您不需要将它们放入解析器规则中:
Remove the literal
' '
from yournames
rule and replace it with aSPACES
token:Or simply discard the spaces at the lexer-level so that you don't need to put them in your parser rules: