如何正确解析引号?

How to parse quotes correctly?

我正在使用 ANTLR 和 Presto 语法来解析 SQL 查询。这是我正在使用的字符串的定义:

STRING
    : '\'' ( ('\' '\'') | ~'\'' | '\'\'' )* '\''
    ;

然而,当我有这样的查询时:

select replace(name,'\'','')
FROM table1;        

它在解析时搞砸了:'\'',' 作为一个字符串。

当我改用以下规则时:

STRING
    : '\'' ( ('\' '\'') | ~'\'')* '\''
    ;

我没有正确解析如下查询:

SELECT * FROM table1 where col1 = 'nir''s'

这当然是合法的查询。

知道我怎样才能同时抓住两者吗?

谢谢, 尼尔。

如果要支持\',不仅要否定单引号,还要否定反斜杠

像这样:

STRING
    : '\'' ( '\' '\''   // match \'
           | ~[\']      // match anything other than \ and '
           | '\'\''      // match ''
           )* 
      '\''
    ;

并考虑到不同的转义字符,这样做:

STRING
    : '\'' ( '\' ~[\r\n] // match \ followed by any char other than a line break
           | ~[\']       // match anything other than \ and '
           | '\'\''       // match ''
           )* 
      '\''
    ;