ANTLR4 Python3 从字符串中删除引号

ANTLR4 Python3 removing quotes from a string

我有一个规则来匹配语法中的一个字符串。我目前需要字符串的内容而不是引号本身,所以我想去掉引号。

StringLiteral
  : UnterminatedStringLiteral '"'
  ;

UnterminatedStringLiteral
  : '"' (~["\\r\n] | '\' (. | EOF))*
  ;

我在 https://theantlrguy.atlassian.net/wiki/spaces/ANTLR3/pages/2687006/How+do+I+strip+quotes 上看到了一个解决方案,但它是旧版本的 ANTLR,我需要将其翻译成 Python3。有人对此有解决方案吗?

ANTLR3 语法:

STRING: '\"' CHARS '\"' {setText(getText().substring(1, getText().length()-1));} ;

在 ANTLR4 中仍然有效。如果您想将 Java 代码移植到 Python,请执行以下操作:

StringLiteral
  : UnterminatedStringLiteral '"' {self.text = self.text[1:-1]}
  ;

如果您还想去除用于转义其他字符的 \,请执行以下操作:

grammar YourGrammarName;

@lexer::header {
import re
}

...

StringLiteral
  : UnterminatedStringLiteral '"' {self.text = re.sub(r'\(.)', '\1', self.text[1:-1])}
  ;