我正在编写一个 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/