这似乎解决了大部分问题,但是由于我不太擅长负前瞻,我无法破解下面唯一失败的案例
这段代码
{*},
递归地用空字符串替换模式
- 然后
{*}
用空字符串替换最后一个
- 剩余的 if 与 then 匹配,
[]
则称该字符串有效,否则无效。
希望你能得到我想要在这里做的事情。
public static boolean isValid(String input){
// Iterates and replaces all but one substring that match {...},
boolean replaced = true;
int oldLength=0, newLength=0;
while(replaced){
oldLength=input.length();
input = input.replaceFirst("\\{[a-z.]+},", "");
newLength=input.length();
if(oldLength==newLength) replaced=false;
}
// Replaces the last {...}
// This one is done separately as comma should not be present in the last part
input = input.replaceFirst("\\{.*?}", "");
//Then if the string remaining is just [] then it is valid
if(input.equals("[]")){
return true;
} else {
return false;
}
}
public static void main(String[] args) {
String[] input = {"[{...},{...},{...}]",
"[{...},{...}]",
"[{...},{...},{...},{...}]",
"[...},{...},{...},{...}]",
"[{...},{...}{...}]",
"[{...},{...},{...},{...}",
"[{...,{...},{...},{...}]",
"[{...},{...},,{...}]",
"[asd{...},{...},{...},{...}]"
};
for (String s : input) {
if(isValid(s)){
System.out.println("VALID");
} else {
System.out.println("ERROR");
}
}
}
}
这输出 -
VALID
VALID
VALID
ERROR
ERROR
ERROR
VALID
ERROR
ERROR
所以这是第三个没有正确处理的案例,即
[{...,{...},{...},{...}]
这确实需要负前瞻,即正则表达式{*},
不应该匹配 a{
如果它出现在 after{
和 before }
。