简体   繁体   English

ANTLR4中的转义报价?

[英]Escape quote in ANTLR4?

I have this grammar : 我有这个语法:

grammar Hello;
STRING : '"' ( ESC | ~[\r\n"])*  '"' ;
fragment ESC : '\\"' ;
r : STRING;

I want when i type a string : 我想输入字符串时:

"my name is : \" StackOverflow \" "

the result will be : 结果将是:

"my name is : "StackOverflow" "

But this is the result when i test it : 但这是我测试时的结果:

在此处输入图片说明

So what should i do to fix it ? 那我该怎么做才能解决呢? Your help will be appreciated . 您的帮助将不胜感激。

There is no way to handle it in your grammar without targeting a specific language. 如果不针对特定的语言,就无法在语法中处理它。 You either strip the slashes when walking your parse tree in a listener or visitor, or embed target specific code in your grammar. 您可以将解析树放在侦听器或访客中时删除斜线,或者将目标特定的代码嵌入语法中。

If Java is your target, you could do this: 如果Java是您的目标,则可以执行以下操作:

STRING
 : '"' ( ESC | ~[\r\n"] )*  '"'
   {
     String text = getText();
     text = text.substring(1, text.length() - 1);
     text = text.replaceAll("\\\\(.)", "$1");
     setText(text);
   }
 ;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM