0

我正在尝试为运算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 + ")";

任何帮助,将不胜感激。

4

2 回答 2

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)
于 2012-04-16T07:24:35.930 回答
-1

您目前没有在代码中使用任何正则表达式。

.Substring()方法找到第一个OR内部mystring并将其拆分为leftright字符串。因此,只有第一个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 + ")";

希望有帮助。

于 2012-04-16T07:18:26.723 回答