Home » Java » Backslashes and single quotes inside a single quoted String using ANTLR

Backslashes and single quotes inside a single quoted String using ANTLR

Posted by: admin June 30, 2018 Leave a comment

Questions:

I’m having quite some trouble parsing a series of Strings which can come by (bothersome enough) with backslashes which might mean a backslash character or escaping a single quote.

To be more precise my strings come by from a Json like this:

"file_path == 'C:\\Windows7\\whatever' or file_path == '\\'")

And my ultimate objective is to find the single quoted Strings inside those double quoted Strings.

Here is the piece of my grammar trying to reflect this:

ESC
  :   '\' ('\"' | '\'' | '\')
  ;

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

My problem came when I got an input like this inside my Json:

"field1": "(log == 'IKEv2 Doesn\'t have a proposal specified')",

which comes to my grammar as:

\"field1\": \"(log == 'IKEv2 Doesn\\'t have a proposal specified')\",

And that fails to recognize the STRING correctly as it finds the quote without being escaped inside it.

Is there a way to get this to work inside my grammar without messing up with the Strings before they reach it?

Answers: