【问题标题】:JavaCC quote with escape character带有转义字符的 JavaCC 引用
【发布时间】:2014-08-01 03:47:23
【问题描述】:

标记可以包含转义字符的引用字符串的常用方法是什么?以下是一些示例:

1) "this is good"
2) "this is\"good\""
3) "this \is good"
4) "this is bad\"
5) "this is \\"bad"
6) "this is bad
7)  this is bad"
8)  this is bad

下面是一个不能正常工作的示例解析器;除了成功解析的示例 4 和 5 之外,它都具有预期的结果。

options
{
  LOOKAHEAD = 3;
  CHOICE_AMBIGUITY_CHECK = 2;
  OTHER_AMBIGUITY_CHECK = 1;
  STATIC = false;
  DEBUG_PARSER = false;
  DEBUG_LOOKAHEAD = false;
  DEBUG_TOKEN_MANAGER = true;
  ERROR_REPORTING = true;
  JAVA_UNICODE_ESCAPE = false;
  UNICODE_INPUT = false;
  IGNORE_CASE = false;
  USER_TOKEN_MANAGER = false;
  USER_CHAR_STREAM = false;
  BUILD_PARSER = true;
  BUILD_TOKEN_MANAGER = true;
  SANITY_CHECK = true;
  FORCE_LA_CHECK = true;
}

PARSER_BEGIN(MyParser)
import java.io.ByteArrayInputStream;
import java.io.UnsupportedEncodingException;
public class MyParser {
    public static void main(String[] args) throws UnsupportedEncodingException, ParseException{
        //note that this conversion to an input stream is only good for small strings
        MyParser parser = new MyParser(new ByteArrayInputStream(args[0].getBytes("UTF-8")));
        parser.enable_tracing();
        parser.myProduction();
        System.out.println("Must have worked!");
    }
}
PARSER_END(MyParser)

TOKEN:
{
<QUOTED: 
    "\"" 
    (
        "\\" ~[]    //any escaped character
        |           //or
        ~["\""]      //any non-quote character
    )* 
    "\""
>
}


void myProduction() :
{}
{
    <QUOTED>
    <EOF>
}

您可以从命令行运行 MyParser,并输入要解析的内容。它将打印“必须有效!”如果它有效,否则抛出错误。

如何更改此解析器以在示例 4 和 5 中正确失败?

【问题讨论】:

    标签: java parsing escaping quotes javacc


    【解决方案1】:

    要修复您的正则表达式,请制作它

    TOKEN: {
    <QUOTED: 
        "\"" 
        (
             "\\" ~[]     //any escaped character
        |                 //or
            ~["\"","\\"]  //any character except quote or backslash
        )* 
        "\"" > 
    }
    

    【讨论】:

    • 谢谢,就像一个魅力。我也认为这将是一个有用的谷歌热门。
    • 大声笑......当你回到答案并想,“敬畏你,upvote!”,然后看到你上次来这里时已经投票了^_^跨度>
    猜你喜欢
    • 1970-01-01
    • 2015-10-27
    • 2015-12-02
    • 2010-09-19
    • 2013-08-16
    • 1970-01-01
    • 2023-04-09
    • 2020-11-29
    • 2013-01-10
    相关资源
    最近更新 更多