java - 输入方案类型的正则表达式

标签 java regex scheme

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

语言。

有点像

(+ (+ a b))

假设我现在想检查语法,如果有 2 个括号已打开,则必须有 2 个其他右括号。我不确定如何使用正则表达式实现这一点。你能帮帮我吗

最佳答案

正则表达式不能将括号配对到任意深度。 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");
}

关于java - 输入方案类型的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7522136/

相关文章:

functional-programming - 为什么 (car '' (a b)) 评估为“报价”?

functional-programming - 在 scheme 中转换具有两次递归调用的函数以使其成为尾递归

scheme - 这段 lisp 代码的 racket 翻译是什么?

java - Mongo Hadoop 连接器问题

java - 在同一个端口上连续运行一个程序

regex - .htaccess 多重重写条件和规则

php - 根据正则表达式验证字符串

java - 无法使用 YAML Spring Profile 禁用 @Cacheable

java - 如何将数据从 fragment 传递到适配器

java - 删除Java中每行末尾的所有空格