我正在尝试为OR
运算符的操作数添加括号。例如,如果我有如下声明,
C>O AND C>4 OR C>0 AND C>5
我想将其格式化如下
(C>O AND C>4) OR (C>0 AND C>5)
我写了一个简单的代码,如下所示。但是,如果字符串具有多个OR
语句,则代码无法正常工作。我被告知正则表达式可以实现这一点。但是我对正则表达式的了解非常少。
string mystring = "C>O AND C>4 OR C>0 AND C>5";
int indexFound = mystring.IndexOf("OR");
string left = mystring.Substring(0, indexFound - 1);
string right = mystring.Substring(indexFound + 2, mystring.Length - (indexFound + 2));
string output = "(" + left + ")" + "OR" + "(" + right + ")";
任何帮助都将不胜感激。
答案 0 :(得分:1)
这是通过正则表达式的方式:
static string AddBracketsToOr(string input)
{
Regex regex = new Regex(@"(?<left>.+[AND|OR].+) OR (?<right>.+[AND|OR].+)");
Match match = regex.Match(input);
if (match == null)
throw new Exception("Wrong input format");
return String.Format("({0}) OR ({1})",
match.Groups["left"], match.Groups["right"]);
}
用法:
var result = AddBracketsToOr("C>O AND C>4 OR C>0 AND C>5");
更新: 适用于
"C>O AND C>4 OR C>0 AND C>5" // (C>O AND C>4) OR (C>0 AND C>5)
"C>9 OR C>O AND C>4 OR C>0 AND C>5" // (C>9 OR C>O AND C>4) OR (C>0 AND C>5)
"C>9 OR C>O OR C>0 AND C>5" // (C>9 OR C>O) OR (C>0 AND C>5)
答案 1 :(得分:-1)
目前您的代码中没有使用任何正则表达式。
.Substring()
方法会在OR
内找到第一个mystring
并将其拆分为left
和right
个子字符串。因此,只能按照您描述的方式处理第一个OR
。
您必须在mystring
上创建一个循环,直到找不到OR
的出现为止。
示例代码
string mystring = "C>O AND C>4 OR C>0 AND C>5";
string output = "";
int indexFound = mystring.IndexOf("OR");
// indexOf returns -1 if the string cannot be found.
// We quit our loop once -1 is returned.
while (indexFound > -1)
{
// Compute the "left" side of our current mystring.
string left = mystring.Substring(0, indexFound - 1);
// And then append it to our final output variable.
output += "(" + left + ")" + "OR";
// Instead of directly adding the "right" side, we
// "shorten" mystring to only contain the right side.
// This effectively "skips" over the "left" and "OR"
// and will allow us to process the remaining "OR"s.
mystring = mystring.Substring(indexFound + 2)
// Finally, we update indexFound to check if there
// are any more "OR"s inside our mystring.
indexFound = mystring.IndexOf("OR");
}
// Before returning, we add the remaining mystring to
// our output. You have to decide whether you want
// to add the parentheses here.
output += "(" + mystring + ")";
希望有所帮助。