これは問題のほとんどを解決するようですが、私はネガティブな先読みがあまり得意ではないため、以下で失敗する唯一のケースをクラックすることができませんでした
このコード
{*},
パターンを空の文字列に繰り返し置き換えます
- 次に、最後の
{*}
文字列を空の文字列に置き換えます
- 残りの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
つまり、正しく処理されていない最後の3番目のケースです。
[{...,{...},{...},{...}]
これには、負の先読みが必要です。つまり、正規表現が前後にある場合は、正規表現{*},
が一致しないようにする必要があります。{
{
}