這是我對這個問題的。我猜這可能會寫得更乾淨,更容易理解,但是... :) 此外,它可能無法在所有情況下正確工作,但您應該明白。我還添加了一些例子。
好的,這裏是帶註釋的代碼。如果你有任何問題隨時問。
static void Main(string[] args)
{
string s = "{ Name, ==, Me, &&, Age, >, 18, ||, City, ==, NewYork }";
bool ok1 = IsValidExpression(s);
s = "{ Name, ==, Me, &&, Age, >, 18 }";
bool ok2 = IsValidExpression(s);
s = "{ Name, ==, ==, Me, &&, Age, >, 18 }";
bool notok = IsValidExpression(s);
s = "{ Name, Me, &&, Age, >, 18 }";
bool notok2 = IsValidExpression(s);
s = "{ Name, ==, Me, &&, Age, > ||, City, ==, NewYork }";
bool notok3 = IsValidExpression(s);
Console.ReadLine();
}
static bool IsValidExpression(string stringToValidate)
{
List<string> tokens = stringToValidate.Replace("{", "").Replace("}", "").Split(',').Select(t => t = t.Trim()).ToList();
List<string> operators = new List<string>() { "==", "!=", "<", ">" };
List<string> boolOps = new List<string>() { "&&", "||" };
//split by and/or
var boolOpsIndexes = tokens.Where(t => boolOps.Contains(t)).Select(t => tokens.IndexOf(t)).ToList();
//check for AND/OR positions
if (boolOpsIndexes.Any(b => b == 0) || boolOpsIndexes.Any(b => b == tokens.Count - 1)) //bool op is at first or last position
return false;
//make "virtual one at the end, so the program enters loop one or more times
boolOpsIndexes.Add(tokens.Count - 1);
int lastOpIndex = 0;
//iterate through all indexes where and/or were found
foreach (var boolOpIndex in boolOpsIndexes)
{
//take expressions from last AND/OR to next one
var tokensPart = tokens.Skip(lastOpIndex).Take(boolOpIndex).ToList();
if (tokensPart.Count != 3) //there is not 3 parts there... not ok
return false;
//if there is more or less than one comparison operator
if (tokensPart.Count(t => operators.Contains(t)) != 1)
return false; //not ok
//check for both sides of operators
int opIndex = tokensPart.Where(t => operators.Contains(t)).Select(t => tokensPart.IndexOf(t)).First();
//check for operators positions
if (opIndex == 0 || opIndex == tokensPart.Count - 1) //operator is at first or last position
return false; //not ok
//check if left and right side od operator contains something and not operator
if (tokensPart[opIndex - 1] != string.Empty && !operators.Contains(tokensPart[opIndex - 1])
&&
tokensPart[opIndex + 1] != string.Empty && !operators.Contains(tokensPart[opIndex + 1]))
continue;
lastOpIndex = boolOpIndex + 1;
}
return true;
}
'tokens.Count'返回什麼?我的理解應該是'11',不是嗎? – HimBromBeere
是用例如所示的花括號書寫的標記器'字符串'嗎? – Nino
過濾器中令牌的數量。對於名稱== Me &&年齡> 18 ||城市==紐約,11是計數 – Jimmy