字符串中的布尔运算符
本文关键字:运算符 布尔 字符串 | 更新日期: 2023-09-27 18:31:09
我正在尝试为运算符的操作数添加一个括号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 + ")";
任何帮助将不胜感激。
以下是通过正则表达式的方法:
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)
您目前没有在代码中使用任何正则表达式。
.Substring()
方法查找mystring
中的第一个OR
,并将其拆分为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 + ")";
希望有帮助。