有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

用于scheme类型输入的java正则表达式

我正在编写一个java程序,它将根据scheme类的输入进行操作

语言方面

差不多

(+ (+ a b))

假设我现在想检查语法,比如如果有两个括号已经打开,那么必须有另外两个结束括号。我不知道如何用正则表达式实现这一点。你能帮我吗


共 (1) 个答案

  1. # 1 楼答案

    正则表达式不能将括号配对到任意深度。Scheme语法不规则

    http://en.wikipedia.org/wiki/Regular_language#The_number_of_words_in_a_regular_language

    Thus, a non-regularity of some language L' can be proved by counting the words in L'. Consider, for example, the Dyck language of strings of balanced parentheses. The number of words of length 2n in the Dyck language is equal to the Catalan number ..., which is not of the form p(n)λn, witnessing the non-regularity of the Dyck language.

    你必须对它进行标记化,然后遍历标记计数帕伦深度,确保最后深度为零,并且永远不会为负

    对于一种简单的语言,它有括号、空格和由字母“a”的重复组成的标识符,你可以这样做

    Patter token = Pattern.compile("[() ]|a+|.", Pattern.DOT_ALL);
    Matcher m = token.matcher(sourceCode);
    int parenDepth = 0;
    while (m.find()) {
      char ch = m.group().charAt(0);
      switch (ch) {
        case '(':
          ++parenDepth;
          break;
        case ')':
          if (parenDepth == 0) {
            fail("Too many close parens");
          }
           parenDepth;
          break;
      }
    }
    if (parenDepth != 0) {
      fail(parenDepth + " unclosed lists");
    }