How to use backslash escape char for new line in JavaCC?

后端 未结 1 1720
情歌与酒
情歌与酒 2021-01-22 03:47

I have an assignment to create a lexical analyser and I\'ve got everything working except for one bit. I need to create a string that will accept a new line, and the string is

1条回答
  •  遥遥无期
    2021-01-22 04:04

    For string literals, JavaCC borrows the syntax of Java. So, a single-character literal comprising a carriage return is escaped as "\r", and a single-character literal comprising a line feed is escaped as "\n".

    However, the processed string value is just a single character; it is not the escape itself. So, suppose you define a token for line feed:

    < LF : "\n" >
    

    A match of the token will be a single line-feed character. When substituting the token in the definition of another token, the single character is effectively substituted. So, suppose you have the higher-level definition:

    < STRING : "\"" (  ) "\"" >
    

    A match of the token will be three characters: a quotation mark, followed by a line feed, followed by a quotation mark. What you seem to want instead is for the escape sequence to be recognized:

    < STRING : "\"" ( "\\n" ) "\"" >
    

    Now a match of the token will be four characters: a quotation mark, followed by an escape sequence representing a line feed, followed by a quotation mark.

    In your current definition, I see that other often-escaped metacharacters like quotation mark and backslash are also being recognized literally, rather than as escape sequences.

    0 讨论(0)
提交回复
热议问题