简体   繁体   English

如何在 ANTLR4 中的字符串中包含引号

[英]How to include quotes in string in ANTLR4

How can I include quotes for string and characters as part of the string.如何将字符串和字符的引号作为字符串的一部分包含在内。 Example is "This is a \\" string" which should result in one string instead of "This is a \\" as one string and string" as an error in this case.示例是"This is a \\" string" ,在这种情况下,它应该导致一个字符串而不是"This is a \\"作为一个字符串和string"作为错误。 The same goes for the characters.对于角色来说也是如此。 Example is '\\'', but in my case it's only '\\'.示例是“\\”,但在我的情况下它只是“\\”。

This is my current solution which works only without quotes.这是我目前的解决方案,仅在没有引号的情况下有效。

CHARACTER : '\\'' ~('\\'')+ '\\'' ;字符:'\\'' ~('\\'')+ '\\'' ;

STRING : '"' ~('"')+ '"' ;字符串:'"' ~('"')+ '"' ;

Your string/char rules don't handle escape sequences correctly.您的字符串/字符规则无法正确处理转义序列。 For the character it should be:对于字符,它应该是:

CHARACTER: '\'' '\\'? '.' '\'';

Here we make the escape char (backshlash) be part of the rule and require an additional char (whatever it is) follow it.在这里,我们使转义字符(反斜杠)成为规则的一部分,并需要一个额外的字符(无论它是什么)跟随它。 Similar for the string:类似于字符串:

STRING: '"' ('\\'? .)+? '"';

By using +?通过使用+? we are telling ANTLR4 to match in a non-greedy manner, stopping at the first non-escaped quote char after the initial one.我们告诉 ANTLR4 以非贪婪的方式进行匹配,在初始字符之后的第一个非转义引号字符处停止。

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

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