我尝试通过在文本框中输入用户输入的字符串中搜索此关键字来实现可以识别AND,OR,NOT运算符的增强文本框,从而改进过滤网格视图的文本框。
我正在尝试使用正则表达式对结果进行分组,但我不是很擅长这个并且我没有得到我想要的结果。
我想要的一个例子如下:
string = "build1 and build2 and build3 or build4 or not build5 and not build6"
导致分割模式:
这是因为我将采用第一个例子并替换为
SomeTable.Name_Of_Build = 'build1' AND
SomeTable.Name_Of_Build = 'build2' AND
....等等
答案 0 :(得分:2)
这对我有用
\ W +(\砂\鼻涕| \ SOR \鼻涕| \砂| \ SOR | $)
答案 1 :(得分:0)
试试这个正则表达式:
(构建[^ B] +)
答案 2 :(得分:0)
我可能会建议您不要使用正则表达式对结果进行分组,而是执行类似的操作。我认为它比试图猜出正确的正则表达式更强大。
string filter = "build1 and buil2 and build3 or build4 or not build5"
list<string> filterTokens = filter.Split(new char[] {' '})
string gridViewFilter = "";
bool notEqual = false;
foreach(string token in filterTokens)
{
if(token == "and")
{
gridViewFilter += "and"
}
else if(token == "or")
{
gridViewFilter += "or"
}
else if(token == "not")
{
notEqual = true;
}
else if(notEqual)
{
gridViewFilter += "SomeTable.Name_Of_Build <> '" + token + "'";
notEqual = false;
}
else
{
gridViewFilter += "SomeTable.Name_Of_Build <> '" + token + "'";
}
}
此外,如果您真的想要实现强大的全功能排序,则需要使用Reverse Polish Notation (RPN)进行调查。它将允许您处理括号和操作顺序。 RPN实现看起来像这样。
private bool CheckForFilterMatch(string filter, List<string> values, bool exactMatch)
{
for (int i = 0; i < values.Count; i++)
{
values[i] = values[i].ToLower();
}
if (filter.Trim() == "")
{
return true;
}
List<string> rpn = GetPostFixNotation(filter);
Stack<bool> output = new Stack<bool>();
foreach (string token in rpn)
{
if (IsValue(token))
{
bool isMatch;
if (exactMatch)
{
isMatch = values.Contains(token.ToLower());
}
else
{
isMatch = false;
foreach (string value in values)
{
isMatch = (value.IndexOf(token.ToLower()) != -1);
if (isMatch) break;
}
}
output.Push(isMatch);
}
else if (IsOperator(token))
{
bool operand1 = output.Pop();
bool operand2 = output.Pop();
if (token == "&")
{
output.Push(operand1 && operand2);
}
if (token == "|")
{
output.Push(operand1 || operand2);
}
}
}
return output.Pop();
}
public List<string> GetPostFixNotation(string filter)
{
if (filter == "")
{
return new List<string>();
}
List<string> postFixNotation = new List<string>();
Queue<string> output = new Queue<string>();
Stack<string> operators = new Stack<string>();
List<string> parsedFilter = ParseFilterTokens(filter);
foreach (string token in parsedFilter)
{
if (IsValue(token))
{
output.Enqueue(token);
}
else if (IsOperatorNoParenth(token))
{
while (operators.Count > 0 && IsOperatorNoParenth(operators.Peek()))
{
if ((operators.Count > 0 && (Precedence(token) <= Precedence(operators.Peek()))))
{
string operatorToReturn = operators.Pop();
output.Enqueue(operatorToReturn);
}
else break;
}
operators.Push(token);
}
else if (token == "(")
{
operators.Push(token);
}
else if (token == ")")
{
while (operators.Count > 0 && operators.Peek() != "(")
{
output.Enqueue(operators.Pop());
}
operators.Pop();
}
}
while (operators.Count > 0)
{
output.Enqueue(operators.Pop());
}
while (output.Count > 0)
{
postFixNotation.Add(output.Dequeue());
}
return postFixNotation;
}